栈(LIFO-last in Frist out)
仅在表尾(栈顶)进行插入删除操作的线性表.
表尾又叫栈顶(top),表头又叫栈底(base)
插入到栈顶叫入栈(push)
删除栈顶元素叫出栈(pop)
队列(FIFO-fist in Frist out)
仅在表尾插入,在表头删除操作的线性表
队列一般以循环队列出现这里也实现循环队列了,其实在任何语言中实现这些本身真没啥意义
插入(入队)删除(出队)
顺序栈
简单方便,但容易溢出(数组大小固定),容易造成溢出
sequence_stack.h
#pragma once
#include<iostream>
using namespace std;
const int MAX_SIZE = 100;
template<class T>
class SequenceStack
{
public:
SequenceStack(); //初始化栈
~SequenceStack(); //析构函数
void destroy(); //销毁栈
bool isEmpty(); //判空
int size(); //元素个数
T top(); //返回栈顶元素
void clear(); //清空栈
void push(const T& element); //插入元素(栈顶,入栈)
void pop(); //删除元素(栈顶,出栈)
private:
T* m_top; //栈顶指针
T* m_base; //栈底指针
int m_size; //栈中元素个数
};
template<class T>
inline SequenceStack<T>::SequenceStack()
{
this->m_base = new T[MAX_SIZE];
if (!m_base)
{
cout << "new overflow" << endl;
exit(1);
}
this->m_top = this->m_base;
this->m_size = MAX_SIZE;
}
template<class T>
inline SequenceStack<T>::~SequenceStack()
{
if (this->m_base)
{
delete[] this->m_base;
this->m_base = nullptr;
this->m_top = nullptr;
this->m_size = 0;
}
}
template<class T>
inline void SequenceStack<T>::destroy()
{
if (this->m_base)
{
delete[] this->m_base;
this->m_base = nullptr;
this->m_top = nullptr;
this->m_size = 0;
}
}
template<class T>
inline bool SequenceStack<T>::isEmpty()
{
if (this->m_base == this->m_top)
{
return true;
}
return false;
}
template<class T>
inline int SequenceStack<T>::size()
{
return this->m_top - this->m_base;
}
template<class T>
inline T SequenceStack<T>::top()
{
// TODO: 在此处插入 return 语句
return *this->m_top;
}
template<class T>
inline void SequenceStack<T>::clear()
{
this->m_top = this->m_base;
}
template<class T>
inline void SequenceStack<T>::push(const T& element)
{
if (this->m_top - this->m_base == MAX_SIZE)
{
cout << "push overflow" << endl;
return;
}
*++m_top = element;
}
template<class T>
inline void SequenceStack<T>::pop()
{
if (this->m_top == this->m_base)
{