数组实现stack

//程序设计:魏洪源

//版权所有,转载请联系:why2942@163.com

//  设计一个栈(Stack)类。栈是一种具有后进先出(LIFO)特

//  点的存储实体。自己设计其中的数据成员和成员函数。要求

//  包含缺省构造函数、拷贝构造函数,其他成员函数自己设计。

#include<iostream>

using namespace std;

const int max=50;

class Stack

{

public:

 Stack();//缺省构造函数

    Stack(const Stack &a);//拷贝构造函数

 bool Push(int item);//进栈

 bool Pop(int &del);//出栈

 bool GetTop(int &topnumber);//取栈顶元素

 bool MakeEmpty();//置空

 bool Display();//打印所有栈元素

 ~Stack();//析构函数

private:

 int *base;

 int top;

    bool IsFull();//判断是否满

    bool IsEmpty();//判断是否为空

};

int main()

{

 cout<<"1. push"<<endl;

 cout<<"2. pop"<<endl;

 cout<<"3. display"<<endl;

 cout<<"4. copy"<<endl;

 cout<<"5. exit"<<endl;

 cout<<"Input numbers to do the operation:";

 

    int oper;

 cin>>oper;

 Stack s;

 do{//循环测试

 if(oper==1)

 {

  cout<<"Input what to push:";

  int p;

  cin>>p;

  if(s.Push(p)) s.Display();

  else cout<<"Stack is full!"<<endl;

 }

 else if(oper==2)

 {

  int dele;

  if(s.Pop(dele))  cout<<"deleted number:"<<dele<<endl;

  else cout<<"Empty Stack"<<endl;

 }

 else if(oper==3)

 {

  s.Display();

 }

 else if(oper==4)

 {

  Stack cpy(s);

  cout<<"New stack :";

  cpy.Display();

 }

 else if(oper==5) break;

 else

 {

  cout<<"Wrong number!"<<endl;

 }

 cout<<"Input numbers to do the operation:";

 cin>>oper;

 }while(oper!=5);

 

 return 0;

}

bool Stack::IsFull()//判断是否满

 {

  if(top>=max-1) return true;

  else return false;

 }

 

bool Stack::IsEmpty()//判断是否为空

 {

  if(top==-1) return true;

  else return false;

 }

Stack::Stack()//缺省构造函数

 {

  base=new int[max];

  top=-1;

 }

Stack::Stack(const Stack &a)//拷贝构造函数

 {

  base=new int[max];

  int i;

  for(i=0;i<=a.top;i++)

   base[i]=a.base[i];

  top=a.top;

 }

bool Stack::Push(int item)//进栈

 {

  if(IsFull()) return false;

  top++;

  base[top]=item;

  return true;

 }

bool Stack::Pop(int &del)//出栈

 {

  if(IsEmpty()) return false;

  del=base[top];

  top--;

  return true;

 }

bool Stack::GetTop(int &topnumber)//取栈顶元素

 {

  if(IsEmpty()) { cout<<"Empty!"<<endl; return false; }

  topnumber=base[top];

  return true;

 }

bool Stack::MakeEmpty()//置空

 {

  top=-1;

  return true;

 }

bool Stack::Display()//打印所有栈元素

 {

  if(top==-1) { cout<<"Empty stack!"<<endl; return true; }

  int i;

  for(i=0;i<=top;i++)

  {

   cout<<base[i]<<"  ";

  }

  cout<<endl;

  return true;

 }

Stack::~Stack()//析构函数

 {

  delete []base;

 }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值