C++DAY6

手动实现顺序栈,要求实现数据结构中,所有栈的相关操作

#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;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值