《数据结构与算法分析(c语言版)》学习笔记③栈

本文介绍了一种使用C语言实现栈的基本方法,包括创建空栈、判断栈是否为空、元素入栈(push)、获取栈顶元素(top)、元素出栈(pop)及清空栈等核心功能。通过具体的代码示例展示了如何利用结构体来组织栈的数据结构。

栈的操作:push pop。
栈的表头依旧不放任何数据。表头即是栈顶,push,pop都在此处进行!

栈的单元组成

typedef struct node
{
	int element;
	node*next;
}node;
创建一个栈
CreateStack(void)
{
	node* S
	S=malloc(sizeof(node));
	if (s==NULL)printf("out of space!!!");
	*S.next=NULL;
	return S;
}
判断一个栈是否为空
isempty( node*S)//输入表头的指针 
{
	return *S.next==NULL;//如果是空栈返回1,不是返回0 
}
进栈操作(push)
void push(int x,node*s)//sΪ±íÍ·µÄÖ¸Õë 
{
	node*temp;
	temp=malloc(sizeof(node));
	if(temp==NULL)printf("out of space!!!");
	*temp.element=x;
	*temp.next=*s.next;
	*s.next=temp;
}

返回栈顶元素
top(node* s)
{
	if (isempty(s)) {printf("empty stack!!!");return 0;}
	else return *(*s.next).element;
}

出栈操作(pop)
pop(node*s)
{
	node* temp;
	if(isempty(s))printf("empty stack!!!");
	else
	{
		temp=*s.next;
		*s.next=*temp.next;
		free(temp);
	}
} 
空栈操作
MakeEmpty(node*s)
{
	while(*s.next!=NULL)
	pop(s);
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值