C++实现 栈的顺序存储(通过动态数组)

前面讲解了通过静态数组,实现顺序栈

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

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值