1. 程式人生 > 其它 >堆疊的鏈式儲存C/C++實現--鏈棧

堆疊的鏈式儲存C/C++實現--鏈棧

堆疊的鏈式儲存實現

堆疊的鏈式儲存C/C++實現--鏈棧


與順序棧相比,鏈棧的優點在於不存在棧滿上溢的問題。鏈棧通常使用單鏈表實現,進棧、出棧操作就是在單鏈表表頭的

插入、刪除操作。用單鏈表實現鏈棧時,使用不帶頭結點的單鏈表較為方便。

鏈棧的儲存型別可描述為:

1 typedef int ElemType;
2 struct Node {
3     ElemType data;  //棧中元素
4     Node* next;     //下一個元素的指標
5 };
6 typedef Node* LinkStack;

這裡data是棧中存放的元素;next指標指向棧的下一個元素。單鏈表頭指標指向棧頂元素,每個元素(包括棧頂元素)在內,

其next指標指向本元素的下一個元素,即剛好比自己早入棧的那個元素。

具體操作實現:

 1 /*  鏈棧
 2 
 3           實現操作:
 4         *1 進棧
 5         *2 出棧
 6         *3 讀棧頂元素
 7         *4 判空
 8 
 9 程式碼使用不帶頭結點的單鏈表實現鏈棧,
10 入棧、出棧操作相當於單鏈表在表頭的
11 插入、刪除操作。
12                             */
13 #include <iostream>
14 #include <cstdio>
15 using
namespace std; 16 17 typedef int ElemType; 18 struct Node { 19 ElemType data; //棧中元素 20 Node* next; //下一個元素的指標 21 }; 22 typedef Node* LinkStack; 23 24 //初始化一個鏈棧 25 void InitLinkStack( LinkStack& S ) 26 { 27 //S永遠指向棧頂元素,初始化時棧為空,S初始化為NULL 28 S = NULL; 29 } 30 31 //判空 32 bool StackEmpty( LinkStack S )
33 { 34 if( S == NULL ) 35 return true; 36 return false; 37 } 38 39 //進棧:將元素x壓入堆疊 40 bool Push( LinkStack& S, ElemType x ) 41 { 42 Node* temp = new Node; 43 temp->data = x; 44 if( S == NULL ) { 45 S = temp; 46 S->next = NULL; 47 return true; 48 } 49 temp->next = S; 50 S = temp; 51 return true; 52 } 53 54 //出棧:將棧頂元素出棧,並將其值用x帶回 55 bool Pop( LinkStack& S, ElemType& x ) 56 { 57 if( S == NULL ) 58 return false; 59 x = S->data; 60 Node* toFree = S; 61 S = S->next; //新棧頂 62 delete toFree; 63 return true; 64 } 65 66 bool GetTop( LinkStack S, ElemType x ) 67 { 68 if( S == NULL ) 69 return false; 70 x = S->data; 71 return true; 72 } 73 74 void test1() 75 { 76 LinkStack S; 77 InitLinkStack(S); 78 for( int i=1; i<=50; i++ ) { 79 if( Push(S,i) ) { 80 cout << "入棧成功,入棧的元素是:" << i << endl; 81 } 82 else cout << "入棧失敗 " << endl; 83 } 84 85 cout << "-------------------------------" << endl; 86 while( !StackEmpty(S) ) { 87 int x = 0; 88 Pop(S,x); 89 cout << x << endl; 90 } 91 92 } 93 94 int main() 95 { 96 test1(); 97 return 0; 98 }