链栈
链栈的表示
- 运算是受限的单链表,只能在链表头部进行操作,故没有必要附加头结点。栈顶指针就是链表的头指针。
C++代码实现
#include<iostream>
#include<stdlib.h>
using namespace std;
#define OVERFLOW -2
#define OK 1
#define ERROR -1
typedef int Status;
typedef int SElemType;
typedef struct StackNode {
SElemType data;
struct StackNode* next;
}StackNode, * LinkStack;
// 链栈初始化
void InitStack(LinkStack& S) {
S = NULL;
}
// 判断链栈是否为空
Status StackEmpty(LinkStack S) {
if (S == NULL) return 1;
else return 0;
}
// 获取栈顶元素
Status GetTop(LinkStack S, SElemType& e) {
if (StackEmpty(S)) return ERROR;
e = S->data;
return OK;
}
// 获取链栈长度
int GetLength(LinkStack S) {
if (StackEmpty(S)) return 0;
LinkStack p;
p = S;
int i = 0;
while (p) {
i++;
p = p->next;
}
return i;
}
// 入栈
Status Push(LinkStack& S, SElemType e) {
LinkStack p;
p = new StackNode;
if (!p) exit(OVERFLOW);
p->data = e;
p->next = S;
S = p;
return OK;
}
// 出栈
Status Pop(LinkStack& S, SElemType& e) {
if (StackEmpty(S)) return ERROR;
LinkStack p;
e = S->data;
p = S;
S = S->next;
delete p;
p = NULL;
return OK;
}
// 创建栈
void Create(LinkStack& S, int m) {
SElemType x;
int i;
for (i = 1; i <= m; i++) {
cout << "请输入第" << i << "个元素: ";
cin >> x;
Push(S, x);
}
}
// 输出栈
void OutPut(LinkStack S) {
LinkStack p;
p = S;
while (p) {
cout << p->data << " ";
p = p->next;
}
cout << endl;
}
int main()
{
/*--------测试----------*/
LinkStack S;
SElemType e;
int m;
// 初始化链栈
InitStack(S);
cout << "请输入链栈的长度: ";
cin >> m;
Create(S, m);
cout << "栈中元素为: ";
OutPut(S);
GetTop(S, e);
cout << "栈顶元素为: " << e << endl;
cout << "栈的长度为: " << GetLength(S) << endl;
cout << "请输入入栈的元素: ";
cin >> e;
Push(S, e);
cout << "栈中元素为: ";
OutPut(S);
Pop(S, e);
cout << "弹出的元素为: " << e << endl;
cout << "栈的长度为: " << GetLength(S) << endl;
cout << "栈中元素为: ";
OutPut(S);
return 0;
}
请输入链栈的长度: 3
请输入第1个元素: 5
请输入第2个元素: 6
请输入第3个元素: 7
栈中元素为: 7 6 5
栈顶元素为: 7
栈的长度为: 3
请输入入栈的元素: 9
栈中元素为: 9 7 6 5
弹出的元素为: 9
栈的长度为: 3
栈中元素为: 7 6 5