链栈的实现 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 }

 

上一篇【堆栈的顺序存储实现】:https://www.cnblogs.com/pkuqcy/p/14963957.html

posted @ 2021-07-08 13:58  Ann-  阅读(282)  评论(0编辑  收藏  举报