1 #include <stdio.h> 2 #include <stdlib.h> 3 4 typedef struct Node 5 { 6 int data; 7 struct Node * pNext; 8 }NODE,*PNODE; 9 10 typedef struct Stack 11 { 12 PNODE pTop; 13 PNODE pBottom; 14 }STACK,*PSTACK ; 15 16 void init(PSTACK pS); 17 18 bool push(PSTACK , int); 19 void traverse(PSTACK ); 20 bool pop(PSTACK,int*); 21 void clear(PSTACK); 22 23 void init(PSTACK pS) 24 { 25 PNODE p = (PNODE)malloc(sizeof(NODE)); 26 if(p ==NULL) 27 { 28 printf("申请动态内存失败!\n"); 29 exit(-1); 30 } 31 p->pNext = NULL; 32 pS->pBottom = p; 33 pS->pTop = p; 34 35 } 36 bool push(PSTACK pS , int val) 37 { 38 PNODE p = (PNODE)malloc(sizeof(NODE)); 39 if(NULL==p) 40 { 41 printf("申请动态内存失败!\n"); 42 exit(-1); 43 } 44 p->data = val; 45 p->pNext = pS->pTop; 46 pS->pTop = p; 47 return true; 48 } 49 bool pop(PSTACK pS,int* val) 50 { 51 if(pS->pTop == pS->pBottom) 52 return false; 53 PNODE p = pS->pTop; 54 *val = p->data; 55 pS->pTop = p->pNext; 56 free(p); 57 p =NULL; 58 return true; 59 } 60 61 void clear(PSTACK pS) 62 { 63 while(pS->pTop != pS->pBottom) 64 { 65 pop(pS); 66 } 67 return; 68 69 } 70 71 void traverse(PSTACK pS) 72 { 73 PNODE p = pS->pTop; 74 while(p->pNext !=NULL) 75 { 76 printf("%d\n",p->data); 77 p = p->pNext; 78 } 79 return; 80 } 81 82 int main(void) 83 { 84 STACK S; 85 int val; 86 87 init(&S);//目的是造出一个空栈 88 push(&S,1);//压栈 89 push(&S,2); 90 push(&S,3); 91 push(&S,4); 92 push(&S,5); 93 push(&S,6); 94 traverse(&S); 95 96 pop(&S,&val); 97 traverse(&S); 98 clear(&S); 99 traverse(&S); 100 101 return 0; 102 }