4.18作业

本文详细介绍了使用C语言实现的顺序栈和链栈数据结构,包括空间分配、栈操作(入栈、出栈、判空)、以及栈的显示和释放函数。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

顺序栈:

#include "seq_stack.h"
seq_p creat_stack()  //从堆区申请顺序栈的空间
{
	seq_p S=(seq_p)malloc(sizeof(seq_stack));
	if(S==NULL)
	{
		printf("空间申请失败\n");
		return NULL;
	}
	bzero(S->data,sizeof(S->data));
	S->top=-1;
	return S;
}
int empty_stack(seq_p S)  //判空
{
	if(S==NULL)
	{
		printf("入参为空,请检查\n");
		return -1;
	}
	return S->top==-1?1:0;
}
int full_stack(seq_p S)  //判满
{
	if(S==NULL)
	{
		printf("入参为空,请检查\n");
		return -1;
	}
	return S->top==MAX-1?1:0;
}
void push_stack(seq_p S,int data)  //入栈、压栈
{
	if(S==NULL)
	{
		printf("入参为空,请检查\n");
		return;
	}
	if(full_stack(S))
	{
		printf("栈已满,不能入栈\n");
		return;
	}
	S->data[++(S->top)]=data;
}
void pop_stack(seq_p S)  //出栈、弹栈
{
	if(S==NULL)
	{
		printf("入参为空,请检查\n");
		return;
	}
	if(empty_stack(S))
	{
		printf("栈为空,无需出栈\n");
		return;
	}
	printf("出栈元素为%d\n",S->data[S->top--]);
}
void show_stack(seq_p S)  //输出
{
	if(S==NULL)
	{
		printf("入参为空,请检查\n");
		return;
	}
	if(empty_stack(S))
	{
		printf("栈为空,无需输出\n");
		return;
	}
	for(int i=S->top;i>=0;i--)
		printf("%-4d",S->data[i]);
	putchar(10);
}
void free_stack(seq_p *S)  //释放顺序栈
{
	if(S==NULL || *S==NULL)
	{
		printf("入参为空,请检查\n");
		return;
	}
	free(*S);
	*S=NULL;
}

链栈:

#include "link_stack.h"
node_p creat_node(int data)  //申请结点
{
	node_p new=(node_p)malloc(sizeof(node));
	if(new==NULL)
	{
		printf("空间申请失败\n");
		return NULL;
	}
	new->data=data;
	return new;
}
void push_stack(node_p *T,int data)  //入栈
{
	node_p new=creat_node(data);
	new->next=*T;
	*T=new;
}
void pop_stack(node_p *T)  //出栈
{
	if(empty_stack(*T))
	{
		printf("栈空,无需出栈\n");
		return;
	}
	node_p del=*T;
	*T=del->next;
	printf("出栈的元素为%d\n",del->data);
	free(del);
}
void show_stack(node_p T)  //输出栈
{
	if(empty_stack(T))
	{
		printf("栈空,无需输出\n");
		return;
	}
	node_p p=T;
	while(p!=NULL)
	{
		printf("%d->",p->data);
		p=p->next;
	}
	printf("NULL\n");
}
int empty_stack(node_p T)  //判空
{
	return T==NULL?1:0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值