c++:栈的基本操作+实例:迷宫求解
生活随笔
收集整理的這篇文章主要介紹了
c++:栈的基本操作+实例:迷宫求解
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
棧的基本操作+實例:迷宮求解
#include<iostream> using namespace std;struct Node {int datai;int dataj;Node* next; }; //棧 struct Stack {Node* pTop; //頂部指針Node* pBottom; //底部指針 }; void Init(Stack* pS);//初始化 //void CreateStack(Stack* pS);//建棧 void Push(Stack* pS, int vali, int valj);//壓棧 bool Pop(Stack* pS);//出棧:把棧頂?shù)慕Y點刪掉 bool getTop(Stack* pS, int& vali, int& valj);//獲得棧頂元素:但不刪除棧頂結點 bool isEmpty(Stack* pS);//判斷棧頂是否為空 int getSize(Stack* pS);//獲取棧的長度 void Travers(Stack* pS);//遍歷棧 int main() {Stack s;int i = 0, j = 0;//定義迷宮矩陣int a[10][10] = { 0,0,0,0,0,0,0,0,0,0,0,1,1,0,1,1,1,0,1,0,0,1,1,0,1,1,1,0,1,0,0,1,1,1,1,0,0,1,1,0,0,1,0,0,0,1,1,1,0,0,//第五行0,1,1,1,0,1,1,1,0,0,0,1,0,1,1,1,0,1,1,0,0,0,0,0,0,1,0,0,1,0,0,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0, };//輸出矩陣/*for (i = 0; i < 10; i++) {for (j = 0; j < 10; j++) {cout << a0[i][j] << " ";//a0[i*columns+j]等價于a0[i][j]}cout << endl;}return 0;*/Init(&s);Push(&s, 1, 1);i = 1; j = 1;//起點//四個方向,從右開始順時針while (i != 8 || j != 8) {//四個方向,從右開始順時針if (a[i+1][j] == 0) {if (a[i][j + 1] == 0) {if (a[i - 1][j] == 0) {if (a[i][j - 1] == 0) {a[i][j] = 0; Pop(&s); getTop(&s, i, j);}else { j--; Push(&s, i, j); a[i][j] = 0;}}else { i--; Push(&s, i, j); a[i][j] = 0;}}else { j++; Push(&s, i, j); a[i][j] = 0;}}else { i++; Push(&s, i, j); a[i][j] = 0;}}// Travers(&s);//新建一個棧接受已壓好的棧用以逆序輸出棧Stack r;Init(&r);for (int n = 0; n < getSize(&s); i++){getTop(&s,i,j);Pop(&s);Push(&r, i, j);}Travers(&r);} //初始化void Init(Stack * pS){pS->pTop = new Node();if (pS->pTop == NULL) {cerr << "動態(tài)內(nèi)存分配失敗!" << endl;exit(1);}pS->pBottom = pS->pTop;//頂部指針和底部指針指向同一個位置pS->pTop->next = NULL; } //建棧 /*void CreateStack(Stack* pS) {int val;cout << "請輸入各個元素值:" << endl;while (cin >> val && val != -1){Push(pS, val);} }*/ //壓棧 void Push(Stack* pS, int vali,int valj) {Node* newNode = new Node();//新建結點if (newNode == NULL) {cerr << "動態(tài)內(nèi)存分配失敗" << endl;exit(1);}newNode->datai = vali;newNode->dataj = valj;newNode->next = pS->pTop;pS->pTop = newNode; } //遍歷棧 void Travers(Stack* pS) {Node* p = pS->pTop;while (p!=pS->pBottom){cout << '('<<p->datai + 1<<','<<p->dataj + 1 <<')'<< "—>";p = p->next;}cout << endl; } //判斷棧是否為空:通過比較棧頂和棧尾是否相等,如相等,說明為空 bool isEmpty(Stack* pS) {if (pS->pTop == pS->pBottom)return true;return false; } //出棧:把棧頂?shù)慕Y點刪掉 bool Pop(Stack* pS) {if (isEmpty(pS))return false;Node* r = pS->pTop;//暫存頂指針pS->pTop = r->next;//棧頂指針下移一個結點delete r;//釋放空間r = NULL;return true; } //獲取棧頂元素:但不刪除棧頂結點 bool getTop(Stack* pS, int& vali,int& valj) {if (isEmpty(pS))return false;vali = pS->pTop->datai;valj = pS->pTop->dataj;return true; } //獲取棧的長度 int getSize(Stack* pS) {int len = 0;Node* p = pS->pTop;while (p != pS->pBottom) {len++;p = p->next;}return len; }總結
以上是生活随笔為你收集整理的c++:栈的基本操作+实例:迷宫求解的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: python:拉格朗日插值实现及求解
- 下一篇: c++:opencv读图后mat矩阵的基