前面讲解了通过静态数组,实现顺序栈
C++实现 栈的顺序存储(通过静态数组)
那么如果我们不想使用定长的数组,转而使用动态数组又该怎么编写呢?强烈建议与上面这篇文章,对比着学习,注重二者不同的地方,这样更能深刻掌握栈的顺序存储
1.栈的结构定义
typedef int ElementType;
#define Maxsize 10
struct Sqstack
{
Element_type *P; //动态数组
int top; //用于指向栈顶位置
};
注意:*P用于指向new开辟的动态数组
2.具体的方法实现,定义一个栈类
class Stack
{
private:
Element_type *P; //动态数组
int top; //用于指向栈顶位置
public:
Stack();
~Stack();
Stack(const Stack& st);
Stack& operator=(const Stack& st);
void Push(const Element_type &element_type);
void Pop();
bool Is_empty()const;
bool Is_full()const;
int Get_Length();
};
在析构函数中使用了new,应该相应的定义一个复制构造函数和运算符重载函数,具体原因请看
C++ 当类的构造函数中使用new关键字时,注意使用复制(拷贝)构造函数,进行深复制
下面是具体方法:
Stack::Stack()
{
P = new Element_type[Maxsize];
top = -1;
}
Stack::~Stack()
{
delete [] P;
}
Stack::Stack(const Stack& st)//注意要进行深复制,把数据也复制
{
this->P = new Element_type[st.top+1];
for (int n = 0; n <= st.top; n++)
this->P[n] = st.P[n];
this->top = st.top;
}
Stack &Stack::operator=(const Stack &st)//注意要进行深复制,把数据也复制
{
this->P = new Element_type[st.top];
for (int n = 0; n <= st.top; n++)
this->P[n] = st.P[n];
this->top = st.top;
return *this;
}
bool Stack::Is_Empty()
{
return(top==-1)
}
bool Stack::Is_Full()
{
return (top==Maxsize-1)
}
void Stack::Push(const Element_type &element_type)
{
if (Is_full())
cout << "已满"<<endl;
else
{
top++;
P[top] = element_type;
}
}
void Stack::Pop()
{
if(Is_empty())
cout << "空栈"<<endl;
else
top--;
}
总结:
①应该将指向动态数组的指针和栈顶top设置为private,这样比起使用struct更简洁
②析构函数为 delete[]P