**1.栈的特点:**先进后出,对数组进行操作,每次只能对栈顶元素操作
**2.栈需要的基本操作:**入栈 (push)、出栈(pop)、取栈顶元素(top)。
入栈:
出栈:
取栈顶元素:
3.程序实现:
程序说明:
(1)用top来表示当前栈中最上面的元素的下标,用count表示当前栈中所存有的数据个数,由于top总是比count少1,所以Stack类中不用单独设私有数据top,用(count-1)来表示即可。
(2)Stack_entry:Stack_entry是栈中元素的类型,使用时根据具体情况赋予类型。例如使用时栈中元素为double类型,则在程序开头声明
typedef double Stack_entry;
(3)Error_code:需要写一个头文件utility.h ,返回值(enum:枚举):
enum Error_code { success, fail, range_error, underflow, overflow, fatal, not_present, duplicate_error, entry_inserted, entry_found, internal_error };
代码:
#include<iostream>
#include"utility.h"
using namespace std;
const int maxstack = 10; //栈的大小,也就是数组的大小
class Stack { //定义一个栈的类
public:
Stack(); //构造函数
bool empty() const; //返回值用bool类型,检测栈中是否有元素,实现过程中并不改变栈中的数据,所以加const。
Error_code pop(); //删除栈顶元素
Error_code top(Stack_entry &item) const;
//读取栈顶元素存入item中,实现过程中并不改变栈中的数据,所以加const。“&item”是引用,为了不必将实参拷贝到形参,节省空间。
Error_code push(const Stack_entry &item); //向栈中存入一个数据item,为了节省空间用引用,但是不能改变原有的数据,所以加const。
private:
int count; //用来记录栈中的有效的元素的个数
Stack_entry entry[maxstack]; //定义一个数组用来存放数据。
};
Error_code Stack::push(const Stack_entry &item) //入栈
{
Error_code outcome = success;
if (count >= maxstack) //判断栈中是否已经存满
outcome = overflow; //若已存满则提示上溢出
else
entry[count++] = item; //若栈中未存满,则将数据存入栈中
return outcome;
}
Error_code Stack::pop() //出栈
{
Error_code outcome = success;
if (count == 0) //判断栈中是否还有元素
outcome = underflow; //若没有则提示下溢出
else --count; //若栈中还有元素则count减一,top向下移一个
return outcome;
}
Error_code Stack::top(Stack_entry &item) const //取栈顶元素放入item中
{
Error_code outcome = success;
if (count == 0) //判断栈中是否还有元素
outcome = underflow; //若没有则提示下溢出
else
item = entry[count - 1]; //若栈中还有元素则将栈顶元素值赋入item中
return outcome;
}
bool Stack::empty() const //判断栈是否为空
{
bool outcome = true;
if (count > 0) outcome = false;
return outcome;
}
Stack::Stack() //构造函数
{
count = 0;
}