链栈基本运算的实现
2011-11-09 21:52
239 查看
//链栈基本运算的实现 #include<iostream> using namespace std; typedef char datatype; typedef struct node * pointer; struct node { datatype data; pointer next; }; //链栈结点类型 typedef struct { pointer top; } lkstack; //链栈类型 //栈的初始化 lkstack* Init_lkstack( ) { lkstack *ls = new lkstack; ls->top = NULL; return ls; } //判栈空 int Empty_lkstack(lkstack *ls) { if(ls->top==NULL) return 1; else return 0; } //入栈 void Push_lkstack(lkstack *ls,datatype x) { pointer p; p=new node; //申请新结点*p p->data=x;; //新结点data域装入x的值 p->next=ls->top; //新结点next为原栈顶 ls->top=p; //新结点为新栈顶 } //出栈 int Pop_lkstack(lkstack *ls,datatype *x) { pointer p; if(ls->top==NULL)//下溢 { cout<<"栈空,不能出栈!\n"; return 0; } else { p=ls->top; *x=p->data; ls->top=p->next; delete p; return 1; } } //取栈顶 int Gettop_lkstack(lkstack *ls,datatype *x) { if(ls->top==NULL)//栈空 { cout<<"栈空,无栈顶可取!\n"; return 0; } else { *x=ls->top->data; return 1; } } void Display(lkstack *ls) { pointer p = ls->top; if(Empty_lkstack(ls)) { cout<<"此时栈为空。"<<endl; } else { cout<<"栈顶到栈底的元素依次是:"; while(p!=NULL) { cout<<p->data<<" "; p = p->next; } cout<<endl; } } int main() { lkstack *S; S=Init_lkstack(); char choice,x; int flag = 1; while(flag) { cout<<"------------链栈------------------------------"<<endl; cout<<" 1. 入栈 "<<endl; cout<<" 2. 出栈 "<<endl; cout<<" 3. 取栈顶元素 "<<endl; cout<<" 4. 判断栈是否为空 "<<endl; cout<<" 5. 浏览栈底到栈顶所有元素(测试用) "<<endl; cout<<" 6. 退出 "<<endl; cout<<"------------------------------------------------"<<endl; cout<<"请选择:"; cin>>choice; switch(choice) { case '1': cout<<"请输入一个需要入栈的字符"<<endl; cin>>x; Push_lkstack(S,x); cout<<"入栈完成"<<endl; break; case '2': if(Pop_lkstack(S,&x)) cout<<"出栈成功,弹出栈的元素是:"<<x<<endl; else cout<<"出栈失败!"<<endl; break; case '3': if(Gettop_lkstack(S,&x)) cout<<"取栈顶元素成功,弹出栈的元素是:"<<x<<endl; else cout<<"取栈顶元素失败!"<<endl; break; case '4': if(Empty_lkstack(S)) cout<<"此时栈为空。"<<x<<endl; else cout<<"此时栈不为空。"<<endl; break; case '5': Display(S); break; case '6': flag=0; break; default : cout<<"输入错误,请重新选择。"<<endl; } } return 0; }
相关文章推荐
- 实现链栈各种基本运算的算法
- 链栈基本运算的实现
- 数据结构第三章实验2.实现链栈的各种基本运算
- 编写一个程序,实现链栈的各种基本运算
- 实验3_2 实现链栈各种基本运算的算法
- 实现链栈各种基本运算
- Java制作计算机并实现基本运算
- 栈-链栈的基本操作及实现
- PL/SQL 实现基本的四则运算
- 队列的顺序存储结构及其基本运算的实现
- 字符串不借助API实现转换可运算基本类型
- 链栈及运算实现
- 实现顺序栈各种基本运算的算法
- 顺序队中实现队列的基本运算
- 串的基本运算实现-加密解密串
- 数据结构 - 数组和广义表的基本运算实现
- 环形队中实现队列的基本运算
- 实验4:栈和队列的基本操作实现及其应用之《链栈》
- 第6次数据结构上机(数组和广义表的基本运算实现)
- 栈的顺序存储结构及其基本运算实现