C++实现一个顺序栈

使用OOP实现一个顺序栈 

#include <iostream>
#include <string>
#include <ctime>

/*
OOP实现栈
*/

using namespace std; 
class SeqStack {
public:
	SeqStack();
	SeqStack(int size);
	SeqStack(const SeqStack &stack);
	~SeqStack();
	void push(int val);	//入栈函数
	void pop();			//出栈函数
	int top();			//返回栈顶元素
	bool empty();		//判断栈空
	bool full();        //判断栈满
private:
	int *_pstack;	//动态开辟数组空间
	int _top;		//标识栈顶元素的下标
	int _size;		//记录数组空间大小
	void extend();	//当栈满的时候,二倍扩容栈
};
void SeqStack::extend()
{
	try {
		int *tmp = new int[2 * _size];
		memcpy(tmp, _pstack, _size * sizeof(int));
		delete[] _pstack;
		_pstack = tmp;
		_size *= 2;
		/*
		_pstack = realloc(_pstack,2 * _size);
		*/

		/*最好用这个------
		for(int i=0;i<_size;i++)
		{
			tmp[i]=_pstack[i];
		}
		*/
	}
	catch (bad_alloc &error)
	{
		cout << "扩容栈内存失败" << endl;
	}

}
SeqStack::SeqStack()
{
	try {
		_pstack = new int[10];
		_top = -1;
		_size = 10;
	}
	catch (bad_alloc &error)
	{
		cout << "初始化,开辟内存失败" << endl;
	}
}
SeqStack::SeqStack(int size)
{
	try {
		_pstack = new int[size];
		_top = -1;
		_size = size;
	}
	catch (bad_alloc &error)
	{
		cout << "初始化,开辟内存失败" << endl;
	}
}
SeqStack::SeqStack(const SeqStack &stack)//拷贝构造函数
{
	_top = stack._top;
	_size = stack._size;
	this->_pstack = new int[_size];
	//memcpy(this->_pstack, stack._pstack, sizeof(int)*_size);
	for (int i = 0; i < _size; i++)
	{
		_pstack[i] = stack._pstack[i];
	}
}

SeqStack::~SeqStack()
{
	delete[] _pstack;
	_pstack = nullptr;
}
void SeqStack::push(int val)
{
	if (full())
	{
		extend();
		push(val);
	}
	else
	{
		_pstack[_top + 1] = val;
		_top++;
	}
}
void SeqStack::pop()
{
	if (empty())
	{
		cout << "当前栈无任何元素" << endl;
	}
	else
	{
		_top--;
	}
}
int SeqStack::top()
{
	if (empty())
	{
		cout << "栈为空" << endl;
		return -1;
	}
	return _pstack[_top];
}
bool SeqStack::empty()
{
	return _top == -1;
}
bool SeqStack::full()
{
	return _top == _size - 1;
}



class CirecleQueue
{
public:
private:
};
void main()
{
	//1
	SeqStack s;
	
	//2设置随机种子
	srand(time(NULL));
	//3
	for (int i = 0; i < 20; i++)
	{
		s.push(rand() % 100 + 1);
	}
	//4
	for (int i = 0; i < 20; i++)
	{
		cout << s.top() << endl;
		s.pop();
	}
	
	

	
	cout<<"hello"<<endl;
	system("pause");
	return;
}

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值