自己实现的栈 用数组实现

#include<iostream>
using namespace std;
const int maxstacksize=50;
///以下为类定义
class stack
{
public:
 stack();
 void push(int a);  //压栈
 int bianli(int n); //遍历并返回栈内某个数据位置
 void output();
 int pop();         //弹栈
 int gettop();      //获取栈顶指针
private:
 int top;
 int stacklist[maxstacksize];

};
//以下为类实现
stack::stack():top(-1)//构造函数
{}
void stack::push(int a)//压栈
{
 if(top==(maxstacksize-1))
 {
  cout<<"the stack is full"<<endl;
  exit(1);
 }
 top++;
 stacklist[top]=a;
}
int stack::bianli(int n) //遍历并返回栈内某个数据位置
{
 bool i;
 i=true;
 int m;
 m=top;
 if(top==-1)
  cout<<"栈为空 找不到要找的元素"<<endl;
 while(m!=-1)
 {
  if(stacklist[m]==n)
  {
   return m;
   i=false;
  }
  m--;
 }
 if(i==true)
  cout<<"没有找到 "<<n<<endl;

}
void stack::output()
{
 int m;
 m=top;
 if(top==-1)
  cout<<"栈为空 不能输出 "<<endl;
 cout<<"栈现在是这个样子地!!!!!!!!!!!!"<<endl;
 while(m!=-1)
 {
  cout<<"       "<<stacklist[m]<<"        "<<endl;
  m--;
 }
}
int stack::pop()
{
 int temp;
 if(top==-1)
  cout<<"栈为空 不能弹栈"<<endl;
 else
 {
  
  temp=stacklist[top];
  top--;
 }
 return temp;
}
int stack::gettop()
{
 return top;
}
///以下为自定义 函数
int selectitem(stack & s,int n)
{
 stack q;
 
 int i,j,t,m,p;
 m=s.bianli(n);//查找位置

 t=s.gettop()-m;      //移动位置
 for(i=0;i<t;i++)
  q.push(s.pop()); 
 p=s.pop();
 for(j=0;j<t;j++)
  s.push(q.pop());
  s.push(p);
 return m;
}
/以下为主函数
int main()
{
 int i, n,q,t,r;
 stack m;
 n=10;
 cout<<"输入 "<<n<<"个存放在栈里的数"<<endl;
 if(n>(maxstacksize-1))
  cout<<"数据太多"<<endl;
 
    for(i=0;i<n;i++)//向栈内存入数据
 {
  cin>>q;
  m.push(q);  
 }
 m.output();
 cout<<"输入你要查找的数"<<endl;
 cin>>t;
 r=selectitem(m,t);
 cout<<t<<"的位置是"<<r<<endl;
 cout<<"变换之后"<<endl;
 m.output();

 return 0;

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值