--
代码//////链栈的初始化,建立,插入,查找,删除。 ////Author:Wang Yong // //Date: 2010.8.19 //////#include#include typedef int ElemType;/////定义链栈的结构类型typedef struct StackNode { ElemType data; //栈的数据 struct StackNode *next; //指针域 } StackNode,*LinkStack;////链栈的初始化LinkStack LinkStackInit(){ LinkStack top; //构造一个空栈 top = (StackNode *)malloc(sizeof(StackNode)); if(!top) printf("OVERFLOW\n"); top = NULL; return top; }///////判断栈空的算法int LinkStackEmpty(LinkStack top){ if(!top) return 1; else return 0;}//////进栈的算法LinkStack LinkStackPush(LinkStack top,ElemType x){ LinkStack p; p = (StackNode *)malloc(sizeof(StackNode)); //创建一个结点 p->data = x; //设置结点的数据域 p->next = top; //设置结点的指针域 top = p; //设置新的栈顶 return top;}//////出栈的算法ElemType LinkStackPop(LinkStack &top)//出栈的时候必须判断是否栈空 { LinkStack p; ElemType x; if(top != NULL) { x = top->data; //取栈顶元素 p = top; //将栈顶结点重置 top = top->next; free(p); //释放原栈顶结点空间 } else printf("stack empty!\n"); return x;} int main(){ LinkStack lstack; lstack = LinkStackInit(); ElemType x; printf("请输入进栈的元素:"); while(scanf("%d",&x) != EOF) { lstack = LinkStackPush(lstack,x); } LinkStack p; for(p = lstack;p != NULL; p = p->next) printf("%d ",p->data); printf("出栈的结果为:"); while(lstack != NULL) printf("%d ",LinkStackPop(lstack)); return 0;}
--