动态栈程序演示

#include<stdio.h>
#include<stdlib.h>
#include<stdbool.h>
struct Node{
	int data;
	struct Node* next;
};
struct Stack{
	struct Node* pTop;
	struct Node* pBottom;
};
void init(struct Stack*);
void push(struct Stack*,int);
bool pop(struct Stack*,int*);
void traverse(struct Stack*);
void clean(struct Stack*);
int main(void)
{
	int val;
	struct Stack S;
	init(&S);
	push(&S,1);
	push(&S,2);
	push(&S,3);
	push(&S,4);
	push(&S,5);
	traverse(&S);
	if(pop(&S,&val))
	{
		printf("出栈的元素是%d\n",val);
	}
	else
	{
		printf("该栈为空,出栈失败!\n");
	}
	traverse(&S);
	clean(&S);
	traverse(&S);
	return 0;
}
void init(struct Stack* pS)
{
	struct Node *s=NULL;
	s=(struct Node*)malloc(sizeof(struct Node));
	if(NULL==s)
	{
		printf("动态内存申请失败!\n");
		exit(-1);
	}
	else
	{
		pS->pTop=s;
		pS->pBottom=s;
		s->next=NULL;
	}
	return;
}
void push(struct Stack* pS,int val)
{
	struct Node *p=(struct Node*)malloc(sizeof(struct Node));
	if(NULL==p)
	{
		printf("动态内存申请失败!\n");
		exit(-1);
	}
	p->data=val;
	p->next=pS->pTop;
	pS->pTop=p;
	return;
}
bool pop(struct Stack* pS,int* pVal)
{
	struct Node *p=NULL;
	if(pS->pBottom==pS->pTop)
	{
		return false;
	}
	else
	{
		p=pS->pTop;
		*pVal=p->data;
		pS->pTop=p->next;
		free(p);
		return true;
	}
}
void traverse(struct Stack* pS)
{
	struct Node *p=pS->pTop;
	while(p!=pS->pBottom)
	{
		printf("%d	",p->data);
		p=p->next;
	}
	printf("\n");
	return;
}
void clean(struct Stack* pS)
{
	struct Node *p=pS->pTop,*q=NULL;
	while(p!=pS->pBottom)
	{
		q=p->next;
		free(p);
		p=q;
	}
	pS->pTop=pS->pBottom;
	return;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值