一、栈的概念
栈(stack)又名堆栈,它是一种运算受限的线性表。限定仅在表尾进行插入和删除操作的线性表。这一端被称为栈顶,相对地,把另一端称为栈底。向一个栈插入新元素又称作进栈、入栈或压栈,它是把新元素放到栈顶元素的上面,使之成为新的栈顶元素;从一个栈删除元素又称作出栈或退栈,它是把栈顶元素删除掉,使其相邻的元素成为新的栈顶元素。
二、栈的实现
栈的基本操作包括增、删、改、查、判空、判满,此篇采用c++实现栈的基本操作。
“utility.h”内容如下:
//枚举
enum Error_code
{
success, fail, range_error, underflow, overflow, fatal,
not_present, duplicate_error, entry_inserted, entry_found,
internal_error
};
“stack.h”内容如下:
const int maxstack = 10; // small value for testing,符号常量
typedef float Stack_entry; // The program will use stacks with float entries.
class Stack
{
public:
Stack(); //构造函数,初始化栈
bool empty() const; //判断栈是否为空,const限定为只读,不能修改栈
Error_code pop(); //删除(弹出)
Error_code top(Stack_entry& item) const; //栈顶操作,const限定为只读,不能修改栈顶元素
Error_code push(const Stack_entry& item); //增加(插入)元素,引用节省时间,空间,const限定为只读,不能修改栈中已有元素
private:
int count; //记录栈已有元素数量
Stack_entry entry[maxstack]; //Stack_entry类型待定
};
“stack.cpp”内容如下:
#include "utility.h"
#include "stack.h"
Stack::Stack()
{
count = 0; //置空栈
}
//若栈满,将outcome置为overflow;否则将item考入entry[]中,并将count++
Error_code Stack::push(const Stack_entry& item)
{
Error_code outcome = success;
if (count >= maxstack)
{
outcome = overflow; //上溢出
}
else
{
entry[count++] = item;
}
return outcome;
}
//如果栈为空,将outcome置为underflow(下溢出);如果栈不为空,将栈顶元素赋值给item
Error_code Stack::top(Stack_entry& item) const
{
Error_code outcome = success;
if (count == 0)
outcome = underflow;
else
item = entry[count - 1];
return outcome;
}
//栈为空,返回true;不为空,返回false
bool Stack::empty() const
{
bool outcome = true;
if (count > 0) outcome = false;
return outcome;
}
//若栈为空,返回underflow;不为空,覆盖栈顶元素
Error_code Stack::pop()
{
Error_code outcome = success;
if (count == 0)
outcome = underflow;
else --count;
return outcome;
}
测试main.cpp
#include <iostream>
using namespace std;
#include "utility.h"
#include "stack.h"
int main()
/*
Pre: The user supplies an integer n and n
floating point numbers.
Post: The floating point numbers are printed in reverse order.
Uses: The class Stack and its methods
*/
{
int n;
float item;
Stack numbers;
cout << " Type in an integer n followed by n floating point numbers.\n"
<< " The numbers will be printed in reverse order." << endl;
cin >> n;
//入栈
for (int i = 0; i < n; i++)
{
cin >> item;
if (numbers.push(item) == overflow)
cout << "\nThe stack is full." << endl;
}
cout << "\n\n";
//出栈
while (!numbers.empty())
{
numbers.top(item); //访问栈顶元素
numbers.pop(); //弹出栈顶元素
cout << item << " ";
}
cout << endl;
cout << "\n\nPlease input a float item for Exit!!!\n";
cin >> item;
return 0;
}
三、结语
以上就是数组实现栈的全部内容啦,当然了,栈还有很多其他的应用,例如括号匹配问题、逆波兰式。更多具体内容,我们下一篇再见吧!