“栈(stack)是限定仅在表尾进行插入和删除操作的线性表。”
栈又称后进先出(LIFO)的线性表,首先它是一个线性表,也就是说,栈元素具有线性关系。
此处直接奉上用数组(封装于类中)实现的线性存储结构栈及双向栈,其中双向栈仅给出了几个必要的类方法,而不包括于主函数中的测试操作。
稍后将奉上链式存储结构栈的代码。
#include <iostream>
#include <cstdio>
using namespace std;
const int maxn=25000;
typedef int ElemType;
class Stack{
private:
ElemType data[maxn+1];
int top;
public:
Stack():top(0) {}
bool push(ElemType n);
bool pop(ElemType *element);
int cnt(){
return top;
}
};
bool Stack::push(ElemType n){
if(top==maxn) return false;
data[++top]=n;
return true;
}
bool Stack::pop(ElemType *element){
if(top==0) return false;
*element=data[top--];
return true;
}
int main()
{
Stack s;//建立栈
int randomNumber=100,e=0,counter=0;
while(randomNumber!=0){
s.push(randomNumber);
randomNumber-=5;
}
counter=s.cnt();
//将一个随机数据压入栈中(随意编写的数据,为了说明问题并测试程序)
//查看栈中数据
while(s.pop(&e)){
cout<<"这是栈中的第"<<counter-s.cnt()<<"个数据,数据值为:"<<e<<"栈中剩余数据个数:"<<s.cnt()<<endl;
}
return 0;
}
以下为双向栈的部分代码,其中仅给出了几个必要的类方法,而不包括主函数。
#include <iostream>
#include <cstdio>
using namespace std;
const int maxn=25000;
typedef int ElemType;
class Stack{
private:
ElemType data[maxn+1];
int top1,top2;
public:
Stack():top1(0),top2(0) {}
bool push1(ElemType n);
bool push2(ElemType n);
bool pop1(ElemType *element);
bool pop2(ElemType *element);
int cnt1(){
return top1;
}
int cnt2(){
return top2;
}
};
bool Stack::push1(ElemType n){
if(top1+1>=top2) return false;
data[++top1]=n;
return true;
}
bool Stack::pop1(ElemType *element){
if(--top1==0) return false;
element=data[top1--];
return true;
}