定义
栈(stack) 是限定仅在表尾进行插入或删除操作的线性表。因此对栈来说,表尾端有特殊含义,成为栈顶(top),表头端称为栈底(bottom),不含元素的空表成为空栈。
栈的基本操作除了在栈顶进行插入或删除,还有栈的初始化,判空及判满等。
栈的表示和实现
栈有两种存储方式:顺序栈,链式栈。本文主要展示顺序栈的实现。
顺序栈,即栈的顺序顺序存储结构是利用一组地址连续的存储单元依次存放自栈底到栈顶的数据元素,同时附设指针top指示栈顶元素在顺序栈中的位置。通常习惯做法是以top=0表示空栈。
// C++ 实现源码
#ifndef STACK_H_
#define STACK_H_
#include <iostream>
template<typename T>
class Stack{
public:
Stack(int stackSize = 10); // 构造函数,构造一个空栈
~Stack(); // 析构函数
bool destory(); // 销毁栈
bool clear(); // 将栈置为空栈
int getLength() const; // 获取栈的长度
T* getContainer(int i = 0) const; // 返回栈首地址
int getTop() const; // 获取栈顶元素
int getBase() const; // 获取栈底元素
bool isEmpty() const; // 判断是否为空栈
bool isFull() const; // 判断是否为满栈
bool push(T data); // 如果栈未满,插入元素,栈顶++
bool pop(T &data); // 如果栈不为空,删除栈顶元素,栈顶--,通过返回删除数据
void traverse() const; // 简单类型的遍历栈
void traverse(void (*callback)(Stack<T> *p)); // 自定义回调函数遍历栈
private:
int top; // 栈顶元素
int base; // 栈底元素
T* container; // 栈指针元素
int stackSize; // 栈已分配的空间
};
template<typename T>
Stack<T>::Stack(int stackSize){
this->stackSize = stackSize;
this->container = new T[this->stackSize];
this->top = 0;
this->base = 0;
}
template<typename T>
bool Stack<T>::destory(){
this->base = 0;
this->top = 0;
delete []this->container; this->container = NULL;
return true;
}
template<typename T>
Stack<T>::~Stack(){
this->destory();
}
template<typename T>
bool Stack<T>::clear(){
this->top = 0;
this->base = 0;
return true;
}
template<typename T>
int Stack<T>::getLength() const{
return this->top - this->base;
}
template<typename T>
T* Stack<T>::getContainer(int i) const{
return (i == 0) ? this->container : &this->container[i];
}
template<typename T>
int Stack<T>::getTop() const{
return this->top;
}
template<typename T>
int Stack<T>::getBase() const{
return this->base;
}
template<typename T>
bool Stack<T>::isEmpty() const{
return this->top == this->base;
}
template<typename T>
bool Stack<T>::isFull() const{
return (this->top - this->base) >= this->stackSize;
}
template<typename T>
bool Stack<T>::push(T data){
if(this->isFull()){ // 判满
return false;
}
this->container[this->top++] = data;
return true;
}
template<typename T>
bool Stack<T>::pop(T &data){
if(this->isEmpty()){ // 判空
return false;
}
data = this->container[--this->top];
return true;
}
template<typename T>
void Stack<T>::traverse() const{
for(int i = this->base; i < this->top; i++){
std::cout << this->container[i] << ",";
}
std::cout << std::endl;
}
template<typename T>
void Stack<T>::traverse( void (*callback)(Stack<T> *p)){
callback(this);
}
#endif /* STACK_H_ */
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。