您的位置:首页 > 其它

数组实现stack

2013-03-26 09:44 323 查看
//程序设计:魏洪源

//版权所有,转载请联系: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;

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: