链栈
链栈:栈的链接存储结构。
和单链表相似,结点结构相同,
不同点是单链表从头结点指向下一个结点
链栈则相反,是栈顶结点指向栈底结点。
只能在栈顶执行插入和删除操作。
入栈示意图
#include "stdafx.h"
#include "malloc.h"
const int STACKSIZE = 5;
void LinkStack();
void Push(int x);
int getTop();
int Pop();
int Empty();
void DeleLinkStack();
typedef int ElemType;
typedef struct Node
{
ElemType data;
Node* next;
}NODE;
NODE* top = (struct Node*)malloc(sizeof(struct Node));
int main()
{
ElemType x;
LinkStack();
int i=1;
while (i<=STACKSIZE)
{
printf("输入需入栈的整数:");
scanf_s("%d", &x);
Push(x);
printf("入栈成功\n");
i++;
}
printf("返回栈顶元素:%d\n", getTop());
//调用析构函数
DeleLinkStack();
while (true)
{
if (Empty()!=1)
{
printf("%d出栈成功\n", Pop());
}
else {
printf("栈空\n");
break;
}
}
return 0;
}
//构造函数,初始化一个空栈链
void LinkStack()
{
top = NULL;
printf("空栈链初始化成功。\n");
}
//入栈
void Push(int x)
{
NODE* s = (struct Node*)malloc(sizeof(struct Node));
s->data = x;
s->next = top;
top = s;
}
//取栈顶元素(并不删除)
ElemType getTop()
{
return top->data;
}
//出栈操作,将栈顶元素弹出
ElemType Pop()
{
NODE* p = NULL;
ElemType x;
if (top == NULL) throw "下溢";
x = top->data;
p = top;
top = top->next;
delete p;
return x;
}
//判断栈是否为空
int Empty()
{
if (top == NULL) return 1;
else return 0;
}
//析构函数,释放链栈各结点的存储空间
void DeleLinkStack()
{
NODE *p = top;
while (top != NULL) {
top = top->next; //top指向被释放结点的下一个结点
printf("即将被删除的栈链结点为%d\n", p->data);
delete p;
p = top; //工作指针p后移,到更新后的top
}
}
运行结果
1、初始化空栈->入栈->返回栈顶元素->出栈
2、初始化空栈->入栈->返回栈顶元素->析构栈
有问题的,望评论区指正。
可以帮助到你的话,麻烦点赞支持一下。