链栈的操作
2017-12-07 22:32
148 查看
//链栈的基本操作 #include <iostream> #include <stdio.h> #include <malloc.h> typedef struct node{ int data; struct node *next; }node,*linkstack; //初始化栈 void init(linkstack *top){ *top=NULL; } //入栈 void push(linkstack *top,int x){ linkstack s = (linkstack)malloc(sizeof(node)); s->data=x; s->next=*top; *top=s; printf("%d 入栈成功!\n",x); } //出栈 void pop(linkstack *top){ linkstack s = (linkstack)malloc(sizeof(node)); int e=0; if(NULL==s) printf("分配失败"); else{ s = *top; e=s->data; *top=s->next; printf("出栈的元素是:%d ",e); } s=NULL; } //取栈顶元素 int gettop(linkstack top){ if(top!=NULL) return top->data; else printf("栈空!不存在栈顶元素!\n"); return 0; } //打印栈内元素 void display(linkstack s) { while(s!=NULL){ printf("%d ",s->data); s=s->next; } } int main() { linkstack s; init(&s); push(&s,2); push(&s,3); display(s); printf("\n"); pop(&s); printf("\n"); push1(&s,4); printf("\n"); int x = gettop(s); printf("栈顶元素是:%d",x); return 0;