#include<stdio.h>
#include<stdbool.h>//c语言中使用bool要包含"stdbool.h"
#include<stdlib.h>
typedef struct Node
{
int data;
struct Node* Next;
}pnode,*P;
typedef struct Stack
{
P top;
P bot;
}stack,*Pstack;
//函数声明
void init(Pstack ps);
void push(Pstack ps,int v);
void traverse(Pstack ps);
bool pop(Pstack ps,int* pv);
bool Is_empty(Pstack ps1);
int main()
{
int val;
stack S;
init(&S);
push(&S,11);
push(&S,22);
printf("遍历前元素为 ");
traverse(&S);//遍历
if(pop(&S,&val))
printf("出栈成功,出栈元素为%d\n",val);
else
printf("出栈失败\n");
printf("遍历后元素为 ");
traverse(&S);
return 0;
}
//栈的创建
void init(Pstack ps)
{
ps->top=(P)malloc(sizeof(pnode));
if(ps->top==NULL)
{
printf("失败\n");
return;
}
else
{
ps->bot=ps->top;
ps->top->Next=NULL;
}
}
//入栈
void push(Pstack ps,int v)
{
P newnode=(P)malloc(sizeof(pnode));
newnode->data=v;
newnode->Next=ps->top;
ps->top=newnode;
return;
}
void traverse(Pstack ps)
{
P r=ps->top;//定义一个临时参数r。遍历时不要去改动原来栈中的top与bot
while(r!=ps->bot)
{
printf("%d ",r->data);
r=r->Next;
}printf("\n");
return;
}
bool Is_empty(Pstack ps1)
{
if(ps1->top==ps1->bot)
return true;
else
return false;
}
//出栈
bool pop(Pstack ps,int* pv)
{
if(Is_empty(ps))
return false;
else
{
P t=ps->top;
*pv=t->data;
ps->top=t->Next;//当栈中元素出去一个,top要向bot移动
free(t);//释放内存
t=NULL;
return true;
}
}