#include <iostream>
using namespace std;
#define INIT_SIZE 10
#define INC_SIZE 10
class SeqStack
{
public:
SeqStack()
{
m_capacity = INIT_SIZE;
m_data = new int[m_capacity];
m_top = 0;
}
~SeqStack()
{
if(m_data != NULL)
{
delete[]m_data;
m_data = NULL;
}
}
bool Inc();//异常安全,若栈满则继续开辟空间
void Push(int v);//插入
void Pop();//删除
bool IsEmpty()const{return m_top == 0 ? true : false;}//判满
bool IsFull()const{return m_top == m_capacity ? true : false;}//判空
bool GetTop(int *value);//获取栈顶元素
void Print();//打印
void Clear();//清除
int size()const{return m_top;}//求栈大小
private:
int *m_data;
int m_capacity;
int m_top;
};
bool SeqStack::Inc()
{
int *temp = new int[m_capacity];
int size = m_capacity;
memcpy(temp,m_data,sizeof(int)*m_capacity);
m_capacity = m_capacity + INC_SIZE;
delete[]m_data;
m_data = new int[m_capacity];
memcpy(m_data,temp,sizeof(int)*size);
delete []temp;
temp = NULL;
return true;
}
bool SeqStack::GetTop(int *value)
{
if(IsEmpty())
return false;
else
*value = m_data[m_top-1];
}
void SeqStack::Print()
{
for(int i = m_top-1;i>=0;i--)
cout<<m_data[i]<<" ";
cout<<endl;
}
void SeqStack::Push(int v)
{
if(!IsFull() || Inc())
m_data[m_top++] = v;
}
void SeqStack::Pop()
{
if(!IsEmpty())
m_top--;
}
数据结构之C++实现顺序栈(SeqStack)(无主函数)
最新推荐文章于 2021-03-18 22:11:33 发布