数据结构之栈

# include <stdio.h>
# include <stdlib.h>

typedef struct Node
{
	int val;
	struct Node * pNext;
}NODE,* PNODE;

typedef struct Stack
{
	PNODE pTop;
	PNODE pBottom;
}STACK,* PSTACK;

void init(PSTACK);			//初始化栈
void push(PSTACK,int);		//压栈
bool pop(PSTACK,int *);		//出栈
void clear(PSTACK);			//清空栈
bool empty(PSTACK);			//检查是否栈空
void traverse(PSTACK);		//遍历栈后输出

int main()
{
	int val;
	STACK s;

	init(&s);

	push(&s,1);
	push(&s,2);
	push(&s,3);
	push(&s,4);
	push(&s,5);
	push(&s,6);
	push(&s,7);

	traverse(&s);

	if (pop(&s,&val))
		printf("出栈成功,出栈的数据为:%d\n",val);
	if (pop(&s,&val))
		printf("出栈成功,出栈的数据为:%d\n",val);
	if (pop(&s,&val))
		printf("出栈成功,出栈的数据为:%d\n",val);

	traverse(&s);

	clear(&s);

	traverse(&s);

	if (empty(&s))
		printf("所有数据出栈成功,现在栈为空!\n");

	return 0;
}

void init(PSTACK ps)
{
	ps->pBottom=(PNODE)malloc(sizeof(NODE));
	ps->pBottom->pNext=NULL;
	ps->pTop=ps->pBottom;
}

void push(PSTACK ps,int val)
{
	PNODE pNew=(PNODE)malloc(sizeof(NODE));
	pNew->val=val;
	pNew->pNext=ps->pTop;
	ps->pTop=pNew;
}

void traverse(PSTACK ps)
{
	PNODE p=ps->pTop;
	while(ps->pBottom!=p)
	{
		printf("%d ",p->val);
		p=p->pNext;
	}
	printf("\n");
}

bool empty(PSTACK ps)
{
	if (ps->pBottom==ps->pTop)
		return true;
	return false;
}

bool pop(PSTACK ps,int * pVal)
{
	if (empty(ps))
		return false;
	
	PNODE p=ps->pTop;
	* pVal=p->val;
	ps->pTop=ps->pTop->pNext;
	p=NULL;
	return true;
}

void clear(PSTACK ps)
{
	PNODE p;

	while(ps->pBottom!=ps->pTop)
	{
		p=ps->pTop;
		ps->pTop=ps->pTop->pNext;
		free(p);
	}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值