# 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);
}
}
数据结构之栈
最新推荐文章于 2023-01-20 18:52:37 发布