#include<stdio.h>
#include<stdlib.h>
#include<malloc.h>
struct node
{
int date;
struct node *pnext;
};
struct stack
{
struct node *ptop;
struct node *pbottom;
};
void init(struct stack *p);//栈初始化函数
bool is_empty(struct stack *p);//判断栈是否为空函数
bool pop(struct stack *p,int *shu);//出栈函数
void push(struct stack *p ,int shu);//压栈函数*/
void traverse(struct stack *p);//栈遍历函数
void clear(struct stack *p) ;//清空栈函数
int main()
{ int val;//用来表示出栈的元素
struct stack s;
init(&s);
push(&s,5);
push(&s,55);
push(&s,545);
push(&s,1258);
traverse(&s);
if( pop(&s,&val) )
{
printf("出栈成功,出栈的元素是:%d\n",val);
}
else
{
printf("出栈失败!\n");
}
if( pop(&s,&val) )
{
printf("出栈成功,出栈的元素是:%d\n",val);
}
else
{
printf("出栈失败!\n");
}
traverse(&s);
clear(&s);
traverse(&s);
push(&s,1258);
traverse(&s);
return 0;
}
void init(struct stack *p)
{
p->ptop=(struct node *)malloc(sizeof(struct node));//这个才要申请分配内存
if(NULL==p->ptop)
{
printf("内存分配失败!\n");
exit(-1);
}
else
{
p->pbottom=p->ptop;
p->ptop->pnext=NULL;//或者p->pbottom->pnext=NULL
}
return ;
}
void traverse(struct stack *p)
{
struct node *ptail=p->ptop;
while(p->pbottom!=ptail)//开始写错了,不要写成NULL!=ptail
{
printf("%d ",ptail->date);
ptail=ptail->pnext;
}
printf("\n");
return ;
}
bool is_empty(struct stack *p)
{
if(p->ptop==p->pbottom)
return true;
else
return false;
}
void push(struct stack *p, int shu)
{
struct node *ptail=(struct node *)malloc(sizeof(struct node));
if(NULL==ptail)//这个能够不用,后面也是
{
printf("内存分配失败!\n");
exit(0);
}
ptail->date=shu;
ptail->pnext=p->ptop;//空栈时能够写ptail->pnext=p->pbottom,因此这点要注意,不能写成 p->pbottom
p->ptop=ptail;
//
printf("\n");
return ;
}
bool pop(struct stack *p,int *shu)//出栈
{
if(is_empty(p))
return false;
else
{
struct node *ptail=(struct node *)malloc(sizeof(struct node));
if(NULL==ptail)
{
printf("内存分配失败!\n");
exit(0);
}
ptail=p->ptop;
*shu=ptail->date;
p->ptop=ptail->pnext;
free(ptail);
ptail=NULL;
return true;
}
}
void clear(struct stack *p)
{
if(is_empty(p))
{
printf("栈为空,不准清空!\n");
}
struct node *ptail=(struct node *)malloc(sizeof(struct node));
if(ptail==NULL)
{
printf("内存分配失败!\n");
exit(0);
}
ptail=p->ptop;
struct node *qtail=ptail->pnext;
while(ptail!=p->pbottom)//这里能够优化
{ free(ptail);
ptail=qtail;
qtail=ptail->pnext;
}
p->ptop=p->pbottom;
return ;
}