栈是一种先进后出的数据结构,FILO(first-in-last-out)。
1.实现方式
1.1 顺序栈
base指向栈底,top指向栈顶元素的下一个。
//const int MAXSIZE = xx;
struct SeqStack{
Ele * base;
Ele * top;
int stacksize;
};
对于顺序栈,也可以动态增加内存,栈满重新分配一块更大的。
空栈:base == top
1.2 链式栈
typedef struct node
{
datatype data; /*数据域*/
struct node * next; /*指针域*/
}LinkStack;
设置栈顶指针 top
- 判断空:top == NULL
- 入栈:
data->next = top;
top = data;
1.3 STL栈
同队列queue一样,栈stack也是阉割版的deque.
deque是双向开口的数据结构,将deque头部封闭就行。这种”修改某物接口,形成另一种接口”性质的称作为适配器.
template <class T,class Sequence=deque<T>>
class stack{
protected:
Sequence s; //底层容器
bool empty(){return s.empty();}
bool pop(){s.pop_back();}
//等等
};
同样,栈可以使用双端开口的list作为底层容器。
操作:
* top
* push
* pop
* size
* empty