對棧的一些簡單操做

#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 ;
相關文章
相關標籤/搜索