向量6(继承)栈操作 C++

这篇博客介绍了如何使用C++创建一个名为CStack的类,该类继承自CVector类并实现栈的基本操作。文章详细阐述了CStack类的构造函数、入栈、出栈、判栈空和判栈满的成员函数实现,并提供了AC代码示例,通过输入样例展示了CStack类在实际应用中的栈操作流程。
摘要由CSDN通过智能技术生成

目录

题目描述

思路分析

AC代码


题目描述

定义CStack类实现栈操作。CStack类继承CVector类,新增私有数据成员:

int top; //栈顶

为CStack类添加构造函数CStack(int n1),初始化栈空间和栈顶。此过程要求调用基类相应构造函数完成栈空间初始化。

为CStack类添加入栈,出栈,判栈空,判栈满的成员函数。

主函数,输入数据,测试CStack类。

输入

第一行栈空间n

对每行测试数据,格式为:操作[数据]。其中操作用in表示入栈,out表示出栈,end表示栈操作结束。

输出

输出栈操作结束后,栈中从底至顶的数据;若为空栈,输出empty。

输入样例1 

5
in 10
in 20
out
in 30
in 40
out
end 
out

输出样例1

10 30

思路分析

用计算机系统1LC-3的知识,用top作为指针偏移量来压栈弹栈。

整个压栈和弹栈的过程通过top偏移量和栈底指针data相加来操作。

然后空栈和满栈的判断也通过比较top和栈的长度来实现。

然后压栈的时候判断栈是否是满栈,弹栈的时候判断栈是否是空栈。

需要注意的就是top的值,top为0的时候应该是第一个进栈的,top为n-1的时候应该是最后一个进栈的,这些在判断栈是否为空和栈是否满了的时候要特别小心。

AC代码

#include<iostream>
#include<string>
using namespace std;
class CVector
{
	protected:
		int* data;
	    int n;
	public:
		CVector(int n1){
			n=n1;
			data=new int[n1];
		}
		void display(){
			int i;
			for(i=0;i<n-1;i++)
			cout<<data[i]<<' ';
			cout<<data[i]<<endl;
		}
		~CVector(){
			if(data)
			delete[] data;
			data=NULL;
		}		
};
class CStack:public CVector{
	int top;
	public:
		CStack(int n1):CVector(n1){top=-1;}
		void push(int num){data[++top]=num;}
		void pop(){top--;}
		bool empty(){if(top==-1)return 1;return 0;}
		bool full(){if(top>=n-1)return 1;return 0;}
		void display(){
			for(int i=0;i<top;i++)
			cout<<data[i]<<' ';
			cout<<data[top]<<endl;
		}
};
int main() {
	int n,num;
	string code;
	cin>>n;
	CStack stack(n);
	while(cin>>code)
	{
		if(code=="in")
		{
			cin>>num;
			if(stack.full()!=1)
			stack.push(num);
		}
		else if(code=="out")
		{
			if(stack.empty()!=1)
			stack.pop();
		}
		else
		{
			if(stack.empty())
			cout<<"empty"<<endl;
			else stack.display();
		}
	}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

MaolinYe(叶茂林)

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值