数据结构-day5

在这里插入图片描述
顺序栈

#include "seq_stack.h"

//初始化
seq_p create_stack()
{
	seq_p s = (seq_p)malloc(sizeof(seq_stack));
	if(s==NULL){
		printf("s is NULL\n");
		return NULL;
	}
	s->top = -1;
	return s;
}

//判空
int empty_stack(seq_p s)
{
	if(s==NULL){
		printf("s is NULL\n");
		return -1;
	}
	return s->top==-1?1:0;
}

//判满
int full_stack(seq_p s)
{
	if(s==NULL){
		printf("s is NULL\n");
		return -1;
	}
	return s->top==MAX-1?1:0;
}

//入栈/压栈
void push_stack(seq_p s,datatype data)
{
	if(s==NULL){
		printf("s is NULL\n");
		return;
	}
	if(full_stack(s)){
		printf("seq_stack is full\n");
		return;
	}
	s->data[++s->top] = data;
}

//出栈/弹栈
datatype pop_stack(seq_p s)
{
	if(s==NULL){
		printf("s is NULL\n");
		return -1;
	}
	if(empty_stack(s)){
		printf("seq_stack is empty\n");
		return -2;
	}
	return s->data[s->top--];
}

//从栈顶到栈底依次输出栈中元素
void show_stack(seq_p s)
{
	int i;
	if(s==NULL){
		printf("s is NULL\n");
		return;
	}
	if(empty_stack(s)){
		printf("seq_stack is empty\n");
		return;
	}
	printf("seq_stack data from top to bottom:");
	for(i=s->top;i>-1;i--){
		printf("%-4d",s->data[i]);
	}
	putchar(10);
}

//释放顺序栈
void free_stack(seq_p *p)
{
	if(p==NULL || *p==NULL){
		printf("p or *p is NULL\n");
		return;
	}
	free(*p);
	*p=NULL;
}

链式栈

#include "link_stack.h"

//创建新结点
node_p create_node(int data)
{
	node_p new = (node_p)malloc(sizeof(node));
	if(new==NULL){
		printf("new is NULL\n");
		return NULL;
	}
	new->data = data;
	return new;
}

//判空
int empty_link(node_p t)
{
	return t==NULL?1:0;
}

//入栈
void push_link(node_p *t,int data)
{
	//不需要进行入参检测,因为t本身就在栈区
	node_p new = create_node(data);
	new->next = *t;
	*t = new;
}

//出栈
void pop_link(node_p *t)
{
	if(empty_link(*t)){
		printf("link_stack is empty\n");
		return;
	}
	node_p p = *t;
	*t = p->next;
	printf("pop element:%d\n",p->data);
	free(p);
}

//输出
void show_link(node_p t)
{
	if(empty_link(t)){
		printf("link_stack is empty\n");
		return;
	}
	node_p p = t;
	while(p!=NULL){
		printf("%d->",p->data);
		p = p->next;
	}
	puts("NULL");
}
  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值