栈 - 链表实现

代码如下:

  1 #include <cstdio>
  2 #include <cstdlib>
  3 
  4 typedef int itemType;
  5 struct Node;
  6 typedef struct Node *pNode;
  7 typedef pNode stack;
  8 
  9 struct Node {
 10     itemType item;
 11     pNode next;
 12 };
 13 
 14 int
 15 IsEmpty(stack s)
 16 {
 17     return s->next == NULL;
 18 }
 19 
 20 void
 21 Pop(stack s)
 22 {
 23     pNode tmp;
 24     if (!IsEmpty(s)) {
 25         tmp = s->next;
 26         s->next = s->next->next;
 27         free(tmp);
 28     }
 29 }
 30 
 31 itemType
 32 Top(stack s)
 33 {
 34     if (!IsEmpty(s)) {
 35         return s->next->item;
 36     } else {
 37         printf("Stack is empty!\n");
 38         return -1;
 39     }
 40 }
 41 
 42 void
 43 Push(itemType x, stack s)
 44 {
 45     pNode tmp;
 46     
 47     tmp = (pNode)malloc(sizeof(struct Node));
 48     if (tmp == NULL) {
 49         printf("Out of space!\n");
 50         return;
 51     } else {
 52         tmp->item = x;
 53         tmp->next = s->next;
 54         s->next = tmp;
 55     }
 56 }
 57 
 58 void
 59 MakeEmpty(stack s)
 60 {
 61     if (s == NULL) {
 62         printf("Must use CreateStack first!\n");
 63         return;
 64     } else {
 65         while (!IsEmpty(s)) {
 66             Pop(s);
 67         }
 68     }
 69 }
 70 
 71 stack
 72 CreateStack(void)
 73 {
 74     stack s;
 75     
 76     s = (stack)malloc(sizeof(struct Node));
 77     if (s == NULL) {
 78         printf("out of space!\n");
 79         return NULL;
 80     }
 81     s->next = NULL;
 82     MakeEmpty(s);
 83     return s;
 84 }
 85 
 86 void
 87 DisposeStack(stack s)
 88 {
 89     pNode tmp, p;
 90     
 91     while(!IsEmpty(s)) {
 92         tmp = s->next;
 93         s->next = tmp->next;
 94         free(tmp);
 95     }
 96     free(s);
 97 }
 98 
 99 int
100 main(int argc, char** argv)
101 {
102     stack s;
103     
104     s = CreateStack();
105     Push(2, s);
106     Push(3, s);
107     Push(5, s);
108     Pop(s);
109     Pop(s);
110     Pop(s);
111     Pop(s);
112     printf("%d\n", Top(s));
113     
114     DisposeStack(s);
115     s = NULL;
116     
117     system("pause");
118     return(0);
119 }

 

posted @ 2014-11-04 20:21  nipan  阅读(232)  评论(0编辑  收藏  举报