#include <stdio.h>
#include <stdlib.h>
typedef struct Node
{
int data ;
struct Node * pNext;
}*PNODE ,NODE ;
typedef struct stack
{
PNODE pTop;
PNODE pBottom;
}*PSTACK ,STACK;
void init(PSTACK pS);
void push(PSTACK pS,int val);
void show(PSTACK pS);
bool is_empty(PSTACK pS);
bool pop(PSTACK pS,int * pVal);
void clear(PSTACK pS);
int main()
{
STACK S ;//定义了一个静态的栈,是程序员不能自己释放的
int val ;
init(&S);
push(&S,1);
push(&S,2);
push(&S,3);
push(&S,4);
show(&S);
if(pop(&S,&val))
{
printf("出栈成功,出栈的元素是:%d\n",val);
}
else printf("出栈失败!");
show(&S);
clear(&S);
show(&S);
}
void init(PSTACK pS)
{
pS->pTop = (PNODE)malloc(sizeof(NODE));
pS->pBottom =pS->pTop ;
pS->pTop->pNext = NULL ;
}
void push(PSTACK pS,int val)
{
PNODE pNew =(PNODE)malloc(sizeof(NODE));
pNew->data =val;
pNew->pNext =pS->pTop;
pS->pTop =pNew ;
}
void show(PSTACK pS)
{
PNODE p =pS->pTop ;
while(p!=pS->pBottom)
{
printf("%d ",p->data);
p=p->pNext ;
}
printf("\n");
}
bool is_empty(PSTACK pS)
{
if(pS->pTop==pS->pBottom)
return true ;
else return false ;
}
bool pop(PSTACK pS,int * pVal)
{
if(is_empty(pS))
{
return false ;
}
else
{
PNODE r = pS->pTop;
*pVal =r->data;
pS->pTop = r->pNext;
free(r);
r=NULL;
}
return true ;
}
void clear(PSTACK pS)
{
if(is_empty(pS))
{
return ;
}
else
{
PNODE p =pS->pTop;
PNODE q ;
while(q!=pS->pBottom)
{
q=p->pNext;
free(p);
p=q ;
}
}
pS->pTop=pS->pBottom;
}