堆栈(英语:stack),也可直接称栈。在计算机科学中,是一种特殊的串行形式的数据结构,它的特殊之处在于只能允许在链结串行或阵列的一端(称为堆栈顶端指标,英语:top)进行加入资料(英语:push)和输出资料(英语:pop)的运算。另外堆栈也可以用一维阵列或连结串行的形式来完成。堆栈的另外一个相对的操作方式称为伫列。
由于堆栈数据结构只允许在一端进行操作,因而按照后进先出(LIFO, Last In First Out)的原理运作。
堆栈数据结构使用两种基本操作:推入(push)和弹出(pop):
- 推入:将数据放入堆栈的顶端(阵列形式或串行形式),堆栈顶端top指标加一。
- 弹出:将顶端数据资料输出(回传),堆栈顶端资料减一。
一个栈的简单实现如下:
#ifndef STACK_H
#define STACK_H
#include <iostream>
using std::ostream;
const int defaultSize = 5;
const int overSize = 2;
template <typename T>
class Stack
{
public:
Stack(int size = defaultSize) : maxSize(size),top(-1)
{
elements = new T[size];//创建数组
}
~Stack()
{
delete []elements;
}
bool isFull() const
{
return top == (maxSize - 1);
}
bool isEmpty() const
{
return top == -1;
}
void makeEmpty()
{
top = -1;
}
int getSize() const
{
return top+1;
}
void push(T &value)
{
if(!isFull())
{
elements[++top] = value;
}
else//栈满
{
resize();
elements[++top] = value;
}
}
bool pop(T &t)
{
if(!isEmpty())
{
t = elements[top--];
return true;
}
else//栈空
{
return false;
}
}
bool getTop(T &t) const
{
if(!isEmpty())
{
t = elements[top];
return true;
}
else//栈空
{
return false;
}
}
friend ostream & operator<< (ostream &out,const Stack<T> &s)
{
out << "the stack top is " << s.top << endl;
for(int i = 0; i <= s.top; i++)
{
cout <<" "<<s.elements[i] ;
}
out << endl;
return out;
}
private:
T *elements;
int top;
int maxSize;
void resize()//每次栈满后需对栈进行扩充
{
T *newElements = new T[maxSize+overSize];
for(int i = 0; i < maxSize;i++)
{
newElements[i] = elements[i];//拷贝原来的数据
}
maxSize += overSize;
delete []elements;
elements = newElements;
}
};
#endif
测试代码如下:
#include "stack.h"
#include <fstream>
using std::cin;
using std::cout;
using std::endl;
using std::ifstream;
int main()
{
Stack<int> sta;
ifstream fin("data.txt");
int data;
while (!fin.eof()){
fin >> data;
sta.push(data);
}
cout << "The initial Stack in the file is:\n" << sta;
cout << "The current size of the Stack is: " << sta.getSize() << endl;
sta.getTop(data);
cout << "The current Top element of the Stack is : " << data << endl;
sta.pop(data);
cout << "\nDo a Pop operation, then the stack is:\n" << sta << endl;
cout << "The data popped is: " << data << endl;
sta.getTop(data);
cout << "The current Top element of the Stack is : " << data << endl;
cout << "\nTest the state of the stack:\n";
if (sta.isEmpty()) cout << "The stack is empty now!\n";
else if (sta.isFull()) cout << "The stack is full now!\n";
else cout << "The stack is not empty and not full now!\n";
cout << "Now make the stack empty, then the state of the stack is:\n";
sta.makeEmpty();
if (sta.isEmpty()) cout << "The stack is empty now!\n";
else if (sta.isFull()) cout << "The stack is full now!\n";
else cout << "The stack is not empty and not full now!\n";
system("pause");
return 0;
}