栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

C语言链栈(基本压栈,弹栈,取栈顶元素)

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

C语言链栈(基本压栈,弹栈,取栈顶元素)

C语言链栈(基本压栈,弹栈,取栈顶元素)

#include 
#include 
#include 

typedef struct StackNode {
	struct StackNode* next;
	int data;
}StackNode, *LinkStack;

//链栈的初始化
void initStackNode(LinkStack* s) {
	*s = NULL;
}
//链栈的入栈
void push(LinkStack* s, int e) {
	StackNode* node = (StackNode*)malloc(sizeof(StackNode));
	node->data = e;
	node->next = *s;
	*s = node;
}

//链栈的弹栈
void pop(LinkStack* s) {
	if (!(*s))
	{
		printf("链栈为空n");
		return;
	}
	StackNode* p = *s;
	*s = (*s)->next;
	free(p);
}

//取出栈顶元素(不弹栈)
void getPop(LinkStack* s, int* res) {
	if (!(*s))
	{
		printf("栈为空n");
		return;
	}
	*res = (*s)->data;
}

//遍历链栈
void show(LinkStack s) {
	if (!s)
	{
		printf("栈为空n");
		return;
	}
	StackNode* p = s;
	int i = 0;
	while (p)
	{
		printf("链表中的第%d个元素是%dn", i++, p->data);
		p = p->next;
	}
}

void main() {
	LinkStack s;
	initStackNode(&s);
	show(s);

	printf("测试入栈n");
	for (int i = 0; i < 10; i++)
	{
		push(&s, i);
	}
	show(s);

	printf("测试弹栈n");
	int res;
	while (s)
	{
		getPop(&s, &res);
		printf("当前栈顶元素是%dn", res);
		pop(&s);
	}
	pop(&s);
}

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/1030760.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号