入栈c语言程序,入栈出栈遍历栈C语言程序

#include

#include

#include

typedef struct Node

{

int data;

struct Node * pNext;

}NODE,* PNODE;

typedef struct Stack

{

PNODE pTop;

PNODE pBottom;

}STACK,* PSTACK;

void init(PSTACK);

void pop(PSTACK ps, int *pval);

bool empty(PSTACK ps);

void traverse(PSTACK ps);

void clear(PSTACK ps);

void push(PSTACK ps,int val);

int main()

{

STACK s;

int val;

init(&s);

push(&s,1);

push(&s,2);

push(&s,3);

push(&s,4);

push(&s,5);

push(&s,6);

traverse(&s);

pop(&s,&val);

printf("出栈的元素值是: %d\n",val);

traverse(&s);

clear(&s);

traverse(&s);

return 0;

}

void init(PSTACK ps)

{

ps->pTop = (PNODE)malloc(sizeof(NODE));

if(NULL == ps->pTop)

{

printf("动态内存分配失败!\n");

exit(-1);

}

else

{

ps->pBottom = ps->pTop;

ps->pTop->pNext = NULL;

}

}

bool empty(PSTACK ps)

{

if(ps->pTop == ps->pBottom)

return true;

else

return false;

}

void push(PSTACK ps,int val)

{

PNODE pNew = (PNODE)malloc(sizeof(NODE));

pNew->data = val;

pNew->pNext = ps->pTop;

ps->pTop = pNew;

}

void pop(PSTACK ps, int *pval)

{

if(empty(ps))

{

return ;//不能写return true,因为void无返回值

}

else

{

PNODE r = ps->pTop;

*pval = r->data;

ps->pTop = r->pNext;

free(r);

r = NULL;

return;

}

}

void traverse(PSTACK ps)

{

PNODE p = ps->pTop;

while(p != ps->pBottom)

{

printf("%d ",p->data);

p = p->pNext;

}

printf("\n");

return;

}

void clear(PSTACK ps)

{

if(empty(ps))

{

return;

}

else

{

PNODE p = ps->pTop;

PNODE q = NULL;

while(p != ps->pBottom)

{

q = p->pNext;

free(p);

p = q;

}

ps->pBottom = ps->pTop;

}

}

0818b9ca8b590ca3270a3433284dd417.png

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值