手动实现顺序栈,要求实现数据结构中,所有栈的相关操作
#include <iostream>
using namespace std;
//定义节点,使用模板类
template<typename Type>
class Node{
private:
Type data;//数据元素
Type* next;//指针域
int top;//栈顶
int maxsize;//栈的最大容量
public:
//定义栈的最大容量
Node(int s);
//析构函数
~Node();
void push(Type d);
void pop();
void output();
};
//定义栈的最大容量
template<typename Type>
Node<Type>::Node(int s):maxsize(s) {
next = new Type[s];
top = 0;//初始化栈顶位置
}
//析构函数
template<typename Type>
Node<Type>::~Node() {
delete []next;
next = nullptr;
}
template<typename Type>
void Node<Type>::push(Type d){//入栈
if(this->top == maxsize){//判满
throw string("栈满");
}
this->next[this->top++] = d;//赋值
cout<<"入栈成功"<<endl;
}
template<typename Type>
void Node<Type>::pop(){//出栈
if(-1 == this->top){//判空
throw string("栈空");
}
cout<<"出栈的是"<<this->next[--this->top]<<endl;//删除
}
template<typename Type>
void Node<Type>::output(){//遍历d
for(int i = 0; i < this->top; i++){
cout<<next[i]<<" ";
}
cout<<" "<<endl;
}
//定义菜单栏
template<typename Type>
void Menu(void)
{
//传栈的最大容量
int size = 0;
cout<<"请输入栈的最大容量>>>";
cin>>size;
Node<int> s(size);
int n = 0;
Type d;
while(1){
NEXT:
cout<<"/----------------/"<<endl;
cout<<"/-----1 入栈-----/"<<endl;
cout<<"/-----2 出栈-----/"<<endl;
cout<<"/-----3 遍历-----/"<<endl;
cout<<"/-----4 退出-----/"<<endl;
cout<<"/----------------/"<<endl;
cout<<"请输入操作码>>>";
cin>>n;
switch(n){
case 1:
cout<<"请输入要入栈的数据>>";//接收数据
cin>>d;
try{s.push(d);}catch(const string str){cout<<str<<endl;}//调用入栈函数并判断错误
break;
case 2:
try{s.pop();}catch(const string str){cout<<str<<endl;}//调用出栈函数并判断错误
break;
case 3:
s.output();//调用输出函数
break;
case 4://结束
goto END;
break;
default:cout<<"输入错误请重新输入;"<<endl;
goto NEXT;
}
}
END:
return;
}
int main(){
Menu<int>();
return 0;
}