#include <stdio.h> #include <malloc.h> #include <stdlib.h> #include <stdbool.h> typedef struct Node { int data;//数据域 struct Node *next;//指针域 } node,*Pnode; typedef struct Stack{ Pnode pTop; Pnode pBottom; }stack,*Pstack; //函数声明 void init(Pstack );//造出一个空栈 void push(Pstack ,int );//压栈 void traverse(Pstack ); bool empty(Pstack); bool pop(Pstack,int *);//出栈 void clear(Pstack);//清空 void init(Pstack p ){ p->pTop=(Pnode) malloc(sizeof(node)); if(NULL==p->pTop){ printf("动态内存分配失败\n"); exit(-1); }else { p->pBottom = p->pTop ; p->pTop->next=NULL; } } void push(Pstack p,int val){ Pnode pNew=(Pnode)malloc(sizeof(node)); pNew->data=val; pNew->next=p->pTop; p->pTop=pNew; return; } void traverse(Pstack p){ Pnode add=p->pTop; while(add!=p->pBottom){ printf("%d ",add->data); add=add->next; } } bool empty(Pstack p){ if(p->pTop==p->pBottom){ return true; }else{ return false; } } bool pop(Pstack p,int * pVal){ if(empty(p)){ return false; }else{ Pnode r=p->pTop; *pVal=r->data; p->pTop=r->next; free(r); r=NULL; return true; } } void clear(Pstack p){ if(empty(p)){ return; }else{ Pnode q=p->pTop; Pnode r=NULL; while(q!=p->pBottom){ r=q->next; free(q); q=r; } p->pTop=p->pBottom; } } int main(void){ stack s; int val; init(&s); push(&s,1); push(&s,2); push(&s,3); push(&s,4); traverse(&s); printf("\n"); if(pop(&s,&val)){ printf("出栈成功,出栈的元素是%d\n",val); }else{ printf("出栈失败\n"); } traverse(&s); clear(&s); traverse(&s); printf("\n"); if(pop(&s,&val)){ printf("出栈成功,出栈的元素是%d\n",val); }else{ printf("出栈失败\n"); } return 0; }
09-02
1363
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)