对栈的一些简单操作

#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 ;

转载于:https://my.oschina.net/u/553254/blog/71987

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值