/************************************************************************* > 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; } } }