目录
链栈的存储方式
可以通过 单链表 的方式来实现,使用链式栈的优点在于它能够克服用数组实现的顺序栈空间利用率不高的特点,但是需要为每个栈元素分配额外的指针空间用来存放指针域。
链栈的表示
链栈是运算受限的单链表,只能在链表头部进行操作。如右图就是一个链栈。
链栈的特点
- 链表的头指针就是栈顶
- 不需要头结点
- 基本不存在栈满的情况
- 空栈相当于头指针指向空
- 插入和删除仅在栈顶处执行
链栈功能函数
bool InitStack(SqStack &S); //1.栈的初始化
bool Push(SqStack &S, ElemType e); //2.入栈
bool Pop(SqStack &S, ElemType &e); //3.出栈
bool Gettop(SqStack &S, ElemType &e); //4.得到栈顶元素
代码实现
#include<bits/stdc++.h>
using namespace std;
typedef int ElemType;
typedef struct StackNode {
ElemType data;
struct StackNode *next;
}StackNode, *LinkStack;
//初始化栈
bool InitStack(LinkStack &S) {
//构造一个空栈,栈顶指针置为空
S = NULL;
return true;
}
//入栈
bool Push(LinkStack &S, ElemType e) {
StackNode *p = new StackNode;
p->data = e;
p->next = S;
S = p;
return true;
}
//出栈
bool Pop(LinkStack &S, ElemType &e) {
if(!S)
return false;
e = S->data;
S = S->next;
return true;
}
//得到栈顶元素
bool Gettop(LinkStack &S, ElemType &e) {
if(!S)
return false;
e = S->data;
return true;
}
int main() {
int n;
ElemType e;
LinkStack st;
InitStack(st);
cout << "栈已经初始化" << endl;
cout << "请输入栈中元素个数:" << endl;
cin >> n;
cout << "请依次输入栈中元素:" << endl;
for(int i = 0; i < n; i++) {
cin >> e;
Push(st, e);
}
cout << "取出栈中所有元素:";
while(true) {
if(Pop(st, e))
cout << e << " ";
else
break;
}
cout << endl;
cout << "在栈中加入一个元素:" << endl;
cin >> e;
Push(st, e);
cout << "此时栈顶元素为:" << e << endl;
Gettop(st, e);
return 0;
}