21xrx.com
2025-03-28 00:01:47 Friday
文章检索 我的文章 写文章
C++顺序栈类的实现代码
2023-07-07 02:31:10 深夜i     14     0
C++ 顺序栈 实现代码

C++中的顺序栈类是一种常用的数据结构类型,它使用数组来实现先进后出的栈结构。下面是C++顺序栈类的实现代码。

#include<iostream>
using namespace std;
const int MaxSize=50;
class SeqStack{
  private:
    int data[MaxSize];
    int top; //栈顶指针
  public:
    SeqStack(); //初始化顺序栈
    ~SeqStack(); //销毁顺序栈
    bool empty(); //判断顺序栈是否为空
    bool full(); //判断顺序栈是否满
    void push(int x); //插入元素到顺序栈
    int pop(); //从顺序栈中删除元素并返回其值
    int gettop(); //获取栈顶元素的值
};
SeqStack::SeqStack()
  top=-1;
SeqStack::~SeqStack(){}
bool SeqStack::empty(){
  if(top==-1)
    return true;
  else
    return false;
}
bool SeqStack::full(){
  if(top==MaxSize-1)
    return true;
  else
    return false;
}
void SeqStack::push(int x){
  if(full())
    cout<<"Stack is full!"<<endl;
  else{
    top++;
    data[top]=x;
    cout<<"Push element "<<x<<" into stack!"<<endl;
  }
}
int SeqStack::pop(){
  if(empty())
    cout<<"Stack is empty!"<<endl;
    return 0;
  
  else{
    int x=data[top];
    top--;
    cout<<"Pop element "<<x<<" from stack!"<<endl;
    return x;
  }
}
int SeqStack::gettop(){
  if(empty())
    cout<<"Stack is empty!"<<endl;
    return 0;
  
  else{
    cout<<"The top element is "<<data[top]<<"."<<endl;
    return data[top];
  }
}
int main(){
  SeqStack stack;
  int choice=0;
  while(true){
    cout<<"====== C++ Sequential Stack ======"<<endl;
    cout<<"1. Push "<<endl;
    cout<<"2. Pop "<<endl;
    cout<<"3. Get top "<<endl;
    cout<<"4. Exit "<<endl;
    cout<<"=================================="<<endl;
    cout<<"Please choose the operation you want to perform: ";
    cin>>choice;
    switch(choice){
      case 1: { //插入元素到顺序栈
        int x;
        cout<<"Please enter the element to be pushed: ";
        cin>>x;
        stack.push(x);
        break;
      }
      case 2: { //从顺序栈中删除元素并返回其值
        stack.pop();
        break;
      }
      case 3: { //获取栈顶元素的值
        stack.gettop();
        break;
      }
      case 4: { //结束程序
        cout<<"Exiting. Goodbye!"<<endl;
        exit(0);
      }
      default:
        cout<<"Invalid choice! Please enter a valid choice."<<endl;
    }
  }
  return 0;
}

以上是C++顺序栈类的实现代码,使用该代码可以方便地实现顺序栈的各种基本操作,包括插入元素、删除元素和获取栈顶元素的值等。在实际应用中,顺序栈类可以作为一种常用的数据结构类型,用于解决各种问题。

  
  

评论区

请求出错了