/************************************************************************* > File Name: stack.c > Author: heathcliff > Mail: ------------------------------ > Created Time: 2016年03月31日 星期四 16時44分40秒 ************************************************************************/ #include<stdio.h> #include<stdlib.h> typedef struct node_stack { int data; struct node_stack *next; }stack_list,*slink; // *slink p至關於stack_list *p slink top = NULL; //設置棧頂爲空,並將其置爲全局變量 int length = 0; /*入棧*/ void push(int x) { slink new; new = (slink) malloc (sizeof(stack_list)); if(!new){ printf("內存分配失敗\n"); exit(1); } else{ new->data = x; new->next = top; top = new; } length ++; } /*出棧*/ int pop() { slink p; //其實這裏p沒什麼用 //可是爲了便與理解,至關於一箇中介變量 int temp; p = top; temp = top->data; if(top == NULL) printf("棧下溢\n"); else{ p = p->next; top = p; length --; } free(p); return temp; } /*獲取棧頂元素*/ int get_top() { int t = -1; if(top != NULL) t = top->data; else printf("棧空\n"); return t; } /*打印棧中元素*/ void print() { slink p; printf("棧中元素以下所示\n"); p = top; while(p !=NULL){ printf("[%d]",p->data); p = p->next; } } /*計算鏈棧的長度*/ int main(void) { int i,N,judge,input,temp; printf("請問您要輸入多少個元素\n"); scanf("%d",&N); printf("請輸入你要入棧的數:"); for(i = 0;i<N;i++){ scanf("%d",&input); push(input); } printf("\n鏈表的長度是:%d",length); print(); for(i = 0;i<N;i++){ printf("\n請問您是否要退棧?是(1),否(0)\n"); scanf("%d",&judge); if(1 == judge){ temp = pop(); printf("您出棧的數是:%d\n",temp); printf("\n鏈表的長度是:%d",length); } else if(0 == judge){ break; } else{ printf("請從新輸入\n"); break; } } }