使用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;
}