数据结构-顺序栈
栈是一种受限的线性表,其受限型体现在所有插入与删除都在表的同一端进行,这一端也称为栈顶。主要以下几个操作
- 向栈内压入一个元素push()
- 从栈顶弹出一个元素(删除)pop()
- 判断栈是否为空empty()
- 返回栈顶但不删除成员top()
本例中栈定义通过C++模板类实现,实现思路及代码来自王治和教授数据结构课堂的总结
栈的c++实现
const int maxStack=8;
typedef int stack_entry;
enum error_code{
success,overflow,underflow,fail
};
template <class stack_entry>
class stack{
private:
int count;
stack_entry entry[maxStack];
public:
stack();
error_code push(const stack_entry &item);
error_code pop();
bool empty() const;
error_code top(stack_entry &item);
};
template <class stack_entry>
stack<stack_entry>::stack()
{
count = 0;
}
//入栈
template <class stack_entry>
error_code stack<stack_entry>::push(const stack_entry &item){
//const修饰函数参数时,该参数在函数内不可改变
//item=1;编译出错
error_code outcome=success;
if(count>=maxStack)
outcome=overflow;
else{
entry[count++]=item;
}
return outcome;
}
//出栈
template <class stack_entry>
error_code stack<stack_entry>::pop(){
error_code outcome=success;
if(count==0)
outcome=underflow;
else
--count;
return outcome;
}
//判断栈是否为空
template <class stack_entry>
bool stack<stack_entry>::empty() const{
bool outcome=true;
if(count>0)
outcome=false;
return outcome;
}
//读出栈顶元素
template <class stack_entry>
error_code stack<stack_entry>::top(stack_entry &item){
error_code outcome=success;
if(count==0)
outcome=fail;
else{
item=entry[count-1];
cout<<item<<endl;
}
return outcome;
}
编写测试代码
#include "stack.cpp"
#include <iostream>
using namespace std;
int main(){
stack<int> intStack;
for(int i=0;i<8;i++){
intStack.push(i);
}
if(intStack.empty())
cout<<"该栈为空!"<<endl;
else{
cout<<"该栈不为空!"<<endl;
}
intStack.pop();
int topItem;
intStack.top(topItem);
cout<<topItem<<endl;
}