数据结构-链栈的基本操作

来源:互联网 发布:外国男朋友 知乎 编辑:程序博客网 时间:2024/06/05 00:11
//链栈的基本操作#include<iostream>using namespace std;typedef char elemtype;typedef struct linknode{elemtype data;struct linknode*next;}linkstack;void gettop(linkstack*&s)//取栈顶元素{if(s->next==NULL)cout<<"error"<<endl;char e=s->next->data;cout<<"栈顶元素:"<<e<<endl;}void popall(linkstack*&s)//全部元素出栈{linkstack*p;if(s->next==NULL)cout<<"error!"<<endl;while(s->next!=NULL){p=s->next;char e=p->data;s->next=p->next;free(p);cout<<e<<"出栈"<<endl;}}void pop(linkstack*&s)//出栈{linkstack*p;if(s->next==NULL)cout<<"error!"<<endl;p=s->next;char e=p->data;s->next=p->next;free(p);cout<<e<<"出栈"<<endl;}void push(linkstack*&s,elemtype e)//进栈{linkstack*p;p=(linkstack*)malloc(sizeof(linkstack));p->data=e;p->next=s->next;s->next=p;cout<<e<<"进栈"<<endl;}void empty(linkstack*s)//判断栈是否为空{if(s->next==NULL)cout<<"空!"<<endl;elsecout<<"非空!"<<endl;}void destroy(linkstack*&s)//销毁栈{linkstack*pre=s,*p=s->next;while(p!=NULL){free(pre);pre=p;p=pre->next;}free(pre);}void init(linkstack*&s)//初始化栈{s=(linkstack*)malloc(sizeof(linkstack));s->next=NULL;}int main(){linkstack*s;init(s);empty(s);push(s,'a');push(s,'b');push(s,'c');push(s,'d');push(s,'e');empty(s);gettop(s);popall(s);empty(s);destroy(s);return 0;}