下面是一个同学的顺序栈的实现代码,这位同学没有按照课本的方法来写,按自己的理解写了一个程序,对这位同学的尝试表示赞,同时,也推荐大家可以自己写出符合相应数据结构的算法程序。
当然,这位同学做的还有很多不合理的地方面,所以请大家上来讨论一下。希望 大家积极发言热烈讨论。对积极表示意思者,将会奖励!
请大家主要从:方法合理科学否?和 算法有无错误两个方面来讨论吧。
同学作业链接:http://blog.youkuaiyun.com/lvhaohang/article/details/40377859
#include<iostream>
using namespace std;
class sqstack
{
private:
int top;
int maxsize;
int *elem;
public:
sqstack(int size) {maxsize=size; elem=new int[maxsize]; top=0; }
~sqstack(){delete []elem;}
int length();
bool empty(){return top==0;}
void push(int e);
void pop(int &e);
void display();
};
int sqstack::length()
{ return top; }
void sqstack::push(int e)
{ elem[top++]=e; }
void sqstack::pop(int &e)
{ if (!empty()) {e=elem[--top]; ; }}
void sqstack::display(){ for(int i=top-1;i>=0;i-- )
{ cout<<elem[i] <<" "; } cout<<endl;}
int main()
{ int i,x,e; sqstack a(100);
cout<<"输入要建立栈的长度:"<<endl;
cin>>x;
for(i=1;i<=x;i++)
{cout<<"请输入要入栈的"<<i<<"个数据:"<<endl;
cin>>e;
a.push (e); }
cout<<"显示队栈中的元素为:"<<endl;
a.display ();
cout<<"输入出栈元素个数:";
cin>>x;
cout<<"出栈元素为:";
for(i=1;i<=x;i++) {a.pop (e); cout<<e<<" "; }
cout<<endl;
cout<<"显示栈中的剩余元素为:"<<endl;
a.display ();
return 0;}