数据结构栈插入和删除的实现
发布网友
发布时间:2022-04-23 17:36
我来回答
共2个回答
热心网友
时间:2022-04-23 19:06
#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;
}
热心网友
时间:2022-04-23 20:24
用模板表示的:
#define STACKINCREMENT 10
template<class T> class SeqStack
{public:
SeqStack(int size);
~SeqStack(){delete []elem;}
int SeqStackEmpty()const//判断栈是否为空,若是返回1,否则返回0
{return top==-1;}
void SeqStackClear(){top=-1;}//将栈清空
int SeqStackLength(){return top+1;}//求栈长度,即栈中数据元素的个数
int SeqStackFull() //判断栈是否满,若满返回1,否则返回0
{return top==maxsize-1; }
T&SeqGetTop();
void Push(const T& e);
T& Pop();
private:
T *elem;//存放栈元素的一维数组
int top;//栈顶元素的数组位置
int maxsize;// 栈数组的容量
};
template<class T>
SeqStack<T>::SeqStack(int size):top(-1),maxsize(size)
{
if(maxsize<1) throw"stack capacity must be>0";
elem=new T[maxsize];
if(elem==0) {cout<<"内存分配失败";exit(0);}
}
template<class T>
T& SeqStack::SeqGetTop()
{
if(SeqStackEmpty()){cout<<"栈空";exit(0);}//若栈空,则停止运行
return elem[top];
}
template<class T>
T& SeqStack<T>::Pop()
{if(SeqStackEmpty()) {cout<<"栈空";exit(0);}
return elem[top--];//返回出栈值后在减一
}
template<class T>
void SeqStack<T>::Push(const T& e)
{
if(SeqStackFull) //若栈满,则对其空间进行扩展
{
T *p=new T[maxsize+STACKINCREMENT];
if(!p) {cout<<"内存溢出";exit(0);}
for(int i=0;i<maxsize;i++) p[i]=elem[i];
delete []elem;
elem=p;p=NULL;
maxsize+=STACKINCREMENT;
}
elem[++top]=e;
}