#include <iostream>
using namespace std;
// 函数结果状态代码
#define TRUE 1
#define FALSE 0
#define OK 1
#define ERROR 0
#define INFEASIBLE -1
#define OVERFLOW -2
#define MAXSIZE 100
// Status 是函数的类型 其值是函数结果状态代码
typedef int Status;
typedef int SElemType;
typedef struct StackNode{
SElemType data;
struct StackNode *next;
}StackNode, *LinkStack;
// 链栈的初始化
Status InitStack(LinkStack &S){
S = NULL;
return OK;
}
// 判断链栈是否为空
Status StackEmpty(LinkStack S){
if(S == NULL) return TRUE;
else return FALSE;
}
// 链栈的入栈
Status Push(LinkStack &S, SElemType e){
StackNode *p = NULL;
p = new StackNode; // 生成新节点p
p->data = e; // 讲新节点数据域置为e
p->next = S; // 讲新节点插入栈顶
S = p; // 修改栈顶指针
return OK;
}
// 链表的出栈
Status Pop(LinkStack &S, SElemType &e){
if (S == nullptr) return ERROR;
StackNode *p = nullptr;
e = S->data;
p = S;
S = S->next;
delete p;
return OK;
}
// 取栈顶元素
SElemType GetTop(LinkStack S){
if (S!= nullptr){
return S->data;
}
}
// 销毁栈
Status DestroyStack(LinkStack &S){
StackNode *p = nullptr;
while (S){
p = S;
S = S->next;
delete p;
}
return OK;
}
// 栈置空操作
Status ClearStack(LinkStack &S
StackNode *p, *q;
p = S;
while (p){
q = p->next;
delete p;
p = q;
}
S = nullptr;
return OK;
}
// 求栈的长度
int StackLength(LinkStack S){
int length = 0;
while (S){
length++;
S = S->next;
}
return length;
}
int main() {
LinkStack S;
SElemType e;
InitStack(S);
Push(S, 11);
Push(S, 22);
Push(S, 33);
int length = StackLength(S);
cout << "链栈长度: " << length << endl;
Status ret = StackEmpty(S);
if (ret == TRUE) cout << "空栈" << endl;
else cout << "非空" << endl;
SElemType temp = GetTop(S);
cout << "栈顶元素: " << temp << endl;
Pop(S, e);
cout << "弹出的栈顶元素: " << e << endl;
ClearStack(S);
ret = StackEmpty(S);
if (ret == TRUE) cout << "空栈" << endl;
else cout << "非空" << endl;
DestroyStack(S);
return 0;
}
栈链
最新推荐文章于 2024-07-09 22:37:42 发布