#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;
}