以下为代码:
1 # include <stdio.h> 2 # include <malloc.h> 3 # include <stdlib.h> 4 5 typedef struct LinkList 6 { 7 int data; 8 struct LinkList * next; 9 }NODE, * PNODE; 10 11 typedef struct Stact 12 { 13 PNODE top; 14 PNODE pbottom; 15 }STACK,* PSTACK; 16 17 void init(PSTACK p); 18 bool Push(PSTACK p,int val); 19 bool Pop(PSTACK p); 20 void Traverse(PSTACK p); 21 bool IsEmpty(PSTACK p); 22 23 int main(int argc, char *argv[]) 24 { 25 STACK stack; 26 init(&stack); 27 Pop(&stack); 28 Push(&stack,1); 29 Push(&stack,2); 30 Push(&stack,3); 31 Push(&stack,4); 32 Push(&stack,5); 33 Traverse(&stack); 34 Pop(&stack); 35 Traverse(&stack); 36 return 0; 37 } 38 void init(PSTACK p){ 39 p->top =(PNODE)malloc(sizeof(NODE)); 40 if(NULL==p->top){ 41 printf("内存分配失败"); 42 exit(-1); 43 } 44 p->pbottom=p->top; 45 p->top->next=NULL; 46 } 47 bool Push(PSTACK p,int val){ 48 PNODE pnode=(PNODE)malloc(sizeof(NODE)); 49 if(NULL==pnode){ 50 printf("内存分配失败"); 51 return false; 52 } 53 pnode->data=val; 54 pnode->next=p->top; 55 p->top=pnode; 56 return true; 57 } 58 bool Pop(PSTACK p){ 59 if(IsEmpty(p)){ 60 printf("栈已空 "); 61 return false; 62 } 63 PNODE pnode=p->top; 64 p->top=p->top->next; 65 free(pnode); 66 } 67 void Traverse(PSTACK p){ 68 PNODE pnode=p->top; 69 while(pnode!=p->pbottom){ 70 printf("%d ",pnode->data); 71 pnode=pnode->next; 72 } 73 printf(" "); 74 } 75 bool IsEmpty(PSTACK p){ 76 if(p->top==p->pbottom) 77 { 78 return true; 79 } 80 return false; 81 }
以下是运行结果: