C语言 链栈

链栈

链栈:栈的链接存储结构。
和单链表相似,结点结构相同,
不同点是单链表从头结点指向下一个结点
链栈则相反,是栈顶结点指向栈底结点
只能在栈顶执行插入和删除操作。

入栈示意图
在这里插入图片描述

#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、初始化空栈->入栈->返回栈顶元素->析构栈
在这里插入图片描述
有问题的,望评论区指正。
可以帮助到你的话,麻烦点赞支持一下。

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值