/*
链式栈的表示和实现
链式栈:采用链式的存储结构实现的栈;通常使用单链表的形式;
2019.04.15
*/
#include<iostream>
#include<string.h>
#include<stdlib.h>
using namespace std;
#define OK 1
#define ERROR 0
#define OVERFLOW -1
typedef int Status;
typedef struct StackNode{
char str;
struct StackNode *next;
}StackNode,*LinkStack;
//链栈的初始化
//算法步骤:
//构造一个空栈,将栈顶指针置空
Status InitStack(LinkStack &S){
//构造一个空栈S,栈顶指针置空
S=NULL;
return OK;
}
//链栈的入栈
//算法步骤:
//1.为入栈元素e分配空间,用指针p指向;
//2.将新结点数据域置为e;
//3.将新结点插入栈顶;
//4.修改栈顶指针为p;
//链栈的入栈实质为链式存储结构中头插入的使用
Status Push(LinkStack &S,char e){
//在栈顶中插入元素e
LinkStack p=new StackNode; //生成新结点
if(p==NULL)
return ERROR; //判断是否申请成功
p->str=e; //将新结点的数据域置为e
p->next=S; //将新结点插入栈顶
S=p; //修改栈顶指针指向p
return OK;
}
//链栈的出栈
//算法步骤:
//1.判断栈是否为空,若空则返回ERROR;
//2.将栈顶元素赋值给e;
//3.临时保存栈顶元素的空间,以备释放;
//4.修改栈顶指针,指向新的栈顶元素;
//5.释放原栈顶元素的空间;
Status Pop(LinkStack &S,char &e){
if(S==NULL)
return ERROR; //栈空
LinkStack p=S; //临时保存栈顶元素空间,以备释放
e=p->str; //将栈顶元素赋值给e
S=S->next; //修改栈顶指针
delete p; //释放原栈顶元素的空间
return OK;
}
//取链栈的栈顶元素
//算法步骤:
//先判断该栈是否为空,若非空则返回当前栈顶元素的值;
char GetTop(LinkStack S){
if(S!=NULL)
return S->str;
return NULL;
}
int main(){
LinkStack S=new StackNode;
while(1){
char tmp;
int option=0;
system("cls");
cout<<"链式栈的实现"<<endl;
cout<<"1.链式栈的初始化"<<endl;
cout<<"2.链式栈的入栈"<<endl;
cout<<"3.链式栈的出栈"<<endl;
cout<<"4.取栈顶元素"<<endl;
cout<<"0.退出"<<endl;
cout<<"Please input number:";
cin>>option;
switch(option){
case 1:
if(InitStack(S)==OK)
cout<<"1.Success!"<<endl;
else
cout<<"1.Error!"<<endl;
system("pause");
break;
case 2:
cout<<"Please input a elem:";
cin>>tmp;
if(Push(S,tmp)==OK)
cout<<"2.Success!"<<endl;
else
cout<<"2.Error!"<<endl;
system("pause");
break;
case 3:
if(Pop(S,tmp)==OK){
cout<<"3.Success!"<<endl;
cout<<"The elem is "<<tmp<<"!"<<endl;
}
else
cout<<"3.Error!"<<endl;
system("pause");
break;
case 4:
if(GetTop(S)!=NULL){
cout<<"4.Success!"<<endl;
cout<<"The elem is "<<GetTop(S)<<"!"<<endl;
}
else
cout<<"4.Error!"<<endl;
system("pause");
break;
case 0:
exit(0);
break;
default:
cout<<"Warming!Your input ERROR!"<<endl;
break;
}
}
return 0;
}
数据结构——链式栈的表示和实现
猜你喜欢
转载自blog.csdn.net/JEYMING/article/details/80054561
今日推荐
周排行