一.栈的接口
#pragma once
#include<iostream>
using namespace std;
const int Max = 20;
class SeqStack
{
private:
//满足关系top+1=size
int* StackArray;//顺序栈
int top;//栈顶元素下标,初始值为-1
int maxSize;//最大长度
int size;//栈长
public:
SeqStack(int maxSize = Max);
bool isEmpty();//判空
void push(int val);//入栈
int pop();//出栈
bool isFull();//判满
void reSize(int newSize);//重新设置长度
int getSize();//计算栈长
int getTop();
int getTopIndex();
void print();
};
二.栈的基本操作
1.栈的初始化
1.将栈顶索引设为-1
2.栈长为0;
SeqStack::SeqStack(int maxSize)
{
if (maxSize > 0)
{
StackArray = new int[maxSize];
if (StackArray == nullptr)
cerr << "存储分配错误" << endl;
top = -1;
size = 0;
this->maxSize = Max;
}
else
{
maxSize = 0;
size = 0;
top = -1;
StackArray = nullptr;
cerr << "无效数组" << endl;
}
}
2.判空/判满
1.当栈顶索引为-1时为空栈
2.当栈顶索引为maxSize-1时满栈
bool SeqStack::isEmpty()
{
return top == -1;
}
bool SeqStack::isFull()
{
return top==maxSize-1;
}
3.栈长的计算
栈长和栈顶索引满足size=top+1;
int SeqStack::getSize()
{
return top+1;
}
4.入栈
1.判断是否为满栈
2.先对栈顶索引自增,再对栈顶索引位置赋值
3.栈长加一
4.时间复杂度为Θ(1)
void SeqStack::push(int val)
{
if (isFull())
cout << "Stack is Full." << endl;
else
{
top++;
StackArray[top] = val;
size++;
}
}
5.出栈
1.检验是否栈空
2.栈顶自减
3.返回自减前栈顶元素
4.时间复杂度为Θ(1)
int SeqStack::pop()
{
if (isEmpty())
cout << "Stack is Empty" << endl;
else
{
size--;
int val = StackArray[top];
top--;
return val;
}
}
6.重新分配大小
1.判断新表长是否合理
2.将maxSize设为新表长
3.重新声明一个新数组
4.将旧数组的数组赋值给新数组
5.删除旧数组
6.将新数组设置为StackArray
void SeqStack::reSize(int newSize)
{
if (newSize <= 0)
cerr << "Invalid Size" << endl;
else
{
int* newStack = new int[newSize];
if(newStack==nullptr)
cerr << "存储分配错误" << endl;
for (int i = 0; i < size; i++)
{
newStack[i] = this->StackArray[i];
}
delete []StackArray;
StackArray = newStack;
}
}