1. 栈
1.1 栈的定义
- 栈是一种插入删除只能在表的末尾进行的线性表,其中允许插入和删除的一端称为栈顶,另一端称为栈底。
- 先进后出,后进先出
1.2栈的操作集
栈的建立:
template<class T>
class Stack
{
public:
Stack(int size);
Stack();
~Stack();
bool IsEmpty();
bool IsFull();
T& GetTop();
bool Push(const T& elem);
bool Pop();
void ClearStack();
int Size();
private:
int MaxSize;
int top;
T* stack;
};
Stack<T>::Stack()
{
this->top = -1;
this->MaxSize = DEFAULTSIZE;
this->stack = new T[this->MaxSize];
}
1.2.1 判断栈是否为空
template <class T>
bool Stack<T>::IsEmpty()
{
if (this->top < 0)
return true;
else
return false;
}
1.2.2 判断栈是否满
template <class T>
bool Stack<T>::IsFull()
{
if (this->top == this->MaxSize)
return true;
else
return false;
}
1.2.3 取栈顶元素
template <class T>
T& Stack<T>::GetTop()
{
if (!IsEmpty())
return this->stack[this->top];
else
throw "异常:T& Stack<T>::GetTop()";
}
1.2.4 出栈
template <class T>
bool Stack<T>::Pop()
{
if (!IsEmpty())
{
this->top--;
return true;
}
else
return false;
}
1.2.5 入栈
template <class T>
bool Stack<T>::Push(const T& elem)
{
if (!IsFull())
{
this->top++;
this->stack[this->top] = elem;
return true;
}
else
return false;
}
1.2.6 清空栈
template <class T>
void Stack<T>::ClearStack()
{
this->top = -1;
}
1.2.7 返回栈的元素数量
template <class T>
int Stack<T>::Size()
{
return this->top+1;
}
2. 队列
2.1 队列的定义
1. 队列也是一种操作受限的线性表,只允许在队列的尾端插入,在队列的头端删除。
2. 先进先出,后进后出
2.2队列的操作集
队列的创建:
template <class T>
class Queue
{
public:
Queue(int size);
Queue();
~Queue();
bool IsEmpty();
bool IsFull();
int size();
bool En_Queue(const T& elem);
T& De_Queue();
void Clear();
private:
int MaxSize;
int front;
int rear;
T* queue;
};
template <class T>
Queue<T>::Queue(int size)
{
MaxSize = size;
front = 0;
rear = 0;
this->queue = new T[MaxSize]{ 0 };
}
template <class T>
Queue<T>::Queue()
{
MaxSize = DEFAULTQUEUESIZE;
front = 0;
rear = 0;
this->queue = new T[MaxSize]{ 0 };
}
2.2.1 判断队列是否为空
template <class T>
bool Queue<T>::IsEmpty()
{
if (rear == front)
return true;
else
return false;
}
2.2.2 判断队列是否满
template <class T>
bool Queue<T>::IsFull()
{
if ((rear + 1) % MaxSize == front)
return true;
else
return false;
}
2.1.3 出队
template <class T>
T& Queue<T>::De_Queue()
{
if (!IsEmpty())
{
front = (front + 1) % MaxSize;
return queue[front];
}
else
throw "异常: T& Queue<T>::De_Queue()";
}
2.2.4入队
template <class T>
bool Queue<T>::En_Queue(const T& elem)
{
if (!IsFull())
{
rear = (rear + 1) % MaxSize;
queue[rear] = elem;
return true;
}
else
return false;
}
2.2.5 清空队列
template <class T>
void Queue<T>::Clear()
{
front = 0;
rear = 0;
}
2.2.6 返回队列长度
template <class T>
int Queue<T>::size()
{
return (rear + MaxSize - front) % MaxSize;
}