堆栈的数组实现

来源:互联网 发布:一个算法应具备的特性 编辑:程序博客网 时间:2024/06/03 02:42

 

#include <iostream>
#include <iomanip>
using namespace std;

 

#define MAXSIZE 20

int top=-1;
int Stack[MAXSIZE];

 

//判断是否为空堆栈
bool IsEmpty()
{
 if(-1==top)
  return true;
 return false;
}

 

//将指定的数据存入堆栈
void push(int data)
{
 if(top>=MAXSIZE)
 {
  cout<<"堆栈已满,无法再加入!\n";
 }
 Stack[++top]=data; //将数据存入堆栈
}

 

//从堆栈取出数据
int pop()
{
 if(IsEmpty())
  return -1;
 else
  return Stack[top--]; //将数据取出后,再将堆栈指针往下移
}

 

int main()
{
 int value;

 cout<<" 堆栈的数组实现\n\n";
 cout<<" 请输入5个数字:";
 for(int i=0;i<5;i++)
 {
  cin>>value;
  push(value);
 }

 

 cout<<"\n 从堆栈取出数据:";
 cout<<"\n===================\n";
 while(!IsEmpty())
 {
  cout<<" 堆栈弹出的数据为:"<<setw(2)<<pop()<<endl;
 }

 cout<<"\n\n";
 return 0;
}

 

0 0