4.18作业

发布于:2024-04-18 ⋅ 阅读:(112) ⋅ 点赞:(0)

顺序栈:

#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;
}