当前位置:网站首页>Vector 6 (inheritance)

Vector 6 (inheritance)

2022-06-23 01:04:00 SZU healing system bug

Catalog

Title Description

Thought analysis

AC Code


Title Description

Definition CStack Class implements stack operations .CStack Class inheritance CVector class , Add private data member :

int top; // To the top of the stack

by CStack Class to add constructors CStack(int n1), Initialize stack space and stack top . This procedure requires calling the corresponding constructor of the base class to complete stack space initialization .

by CStack Class add stack , Out of the stack , Judge stack empty , The member function that determines whether the stack is full .

The main function , input data , test CStack class .

Input

The first row of stack space n

Test data for each line , The format is : operation [ data ]. Among them, the operating function is in Means put on the stack ,out Show the stack ,end Indicates the end of stack operation .

Output

After the output stack operation , Bottom to top data in the stack ; If empty stacks , Output empty.

sample input 1 

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

sample output 1

10 30

Thought analysis

With a computer system 1LC-3 Knowledge , use top As a pointer offset to press the stack bounce stack .

AC Code

#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();
		}
	}
}
原网站

版权声明
本文为[SZU healing system bug]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/173/202206221409100382.html