c++实现的顺序栈

栈是一种运算受限的线性表,是一种先进后出的数据结构,限定只能在一端进行插入和删除操作,允许操作的一端称为栈顶,不允许操作的称为栈底 

因此需要的成员变量如下

int  *_stack;    //指向申请的空间的首地址
int top;           //记录栈顶的位置
int size;         //记录申请空间的大小

具体如下封装在类中

#include<iostream>
#include<stdlib.h>
#include<string.h>
using namespace std;
class SeqStack
{
  public:
    SeqStack(int size=10)       //构造函数   初始化
    {
     _stack=new int[size];     
     _top=0;
     _size=size;
    }
    SeqStack(const SeqStack &src)   // 拷贝构造函数(防止浅拷贝)
    {
      _stack=new int[src._size];
      int i=0;
      for(;i<src._top;i++)
      {
        _stack[i]=src._stack[i];
      }
      _size=src._size;
      _top=src._top;
    }
    SeqStack(SeqStack &&src)       //右值拷贝函数  防止临时量的空间时间的浪费
    {
      _stack=src._stack;
      _size=src._size;
      _top=src._top;
      src._stack=nullptr;
    }
    SeqStack & operator=(const SeqStack &src)      //赋值构造函数  返回地址  实现连续赋值
    {
      if(this==&src)
      {
        return *this;
      }
      delete[]_stack;
      _stack=new int[src._size];
      int i=0;
      for(;i<src._top;i++)
      {
        _stack[i]=src._stack[i];

      }
      _size=src._size;
      _top=src._top;
      return *this;
    }
    SeqStack & operator=( SeqStack &&src)  // 右值赋值构造函数 防止临时量对空间时间的浪费
    {
      delete []_stack;
      _stack=src._stack;
      _size=src._size;
      _top=src._top;
      src._stack=nullptr;
      return *this;
    }
   ~SeqStack()      // 析构函数
   {
     delete[]_stack;
     _stack=nullptr;
   }
   void push(int val)  // 栈顶插入
   {
     if(full())
     {
       resize();          // 调用2倍扩容
     }
     _stack[_top]=val;
     _top++;
   }
   void pop()          //  栈顶删除
   {
     if(empty())
     {
      return;

     }
     _top--;
   }
   int top()        //返回栈顶元素
   {
     return mpstack[_top-1];
   }
   bool empty()      // 是否为空
   {
    return _top==0;
   }
   bool full()     //  是否为满
   {
     return _top==_size;
   }
  private:
    int *_stack;
    int _top;
    int _size;
    void resize()    //  2倍扩容函数
    {
     int *s=new int[_size*2];
     int i=0;
     for(;i<_size;i++)
     {
     s[i]= _stack[i];
     }
     delete []_stack;
     _stack=s;
     _size=2*_size;
    }
};
int main()
{
    SeqStack st1(20);
    SeqStack st2(st1);
    SeqStack st3=st1;
    st2=st1;
      st1.push(1);
      cout<<st1.top()<<endl;
    cout<<endl;
    return 0;
}

猜你喜欢

转载自www.cnblogs.com/lc-bk/p/11571728.html