题目:有两个相同的栈A和B,在栈A中存放着从大到小的数:1,2,3,4,5,栈顶为最小数1,另外一个栈B为空的。现在要求不使用其他的数据结构,将栈A中的数字顺序倒过来,使其栈顶的数为最大值5。


解题思路:

  1. 这道题目有一个非常直观的思路。首先栈A中存放着1,2,3,4,5这样5个数字,栈顶元素为1,我们需要将其倒序为5,4,3,2,1。
  2. 我们首先需要将栈顶的最小值1取出来存放在临时变量temp中,然后将剩下的四个数字2,3,4,5转移到栈B中去,再将刚才存放在临时变量中的1插入到栈A中,最后将栈B中的数字转移回到栈A,此时栈A中有一个书是排序好的,就是栈底的1。
  3. 重复上面的思路,这回我们取出栈顶的最小值2存放在临时变量中,将其余剩下的3,4,5转移到栈B中,然后再将2插入栈A中。

代码实例


面试题:利用一个栈倒序另外一个栈中的数_数据结构面试题:利用一个栈倒序另外一个栈中的数_ios_02View Code


#include<iostream>
#include<stdlib.h>
#include<stack>
using namespace std;

template <typename T> void ReverseOrder(stack<T> &s1,stack<T> &s2)
{
s1.push(5);
s1.push(4);
s1.push(3);
s1.push(2);
s1.push(1);

int sortNum=0;
int oriStackSize=s1.size();
while(sortNum<oriStackSize)
{
int temp=s1.top();
s1.pop();
while(s1.size()-sortNum>0)
{
s2.push(s1.top());
s1.pop();
}
//首元素存入s1
s1.push(temp);
++sortNum;

while(!s2.empty())
{
s1.push(s2.top());
s2.pop();
}

}

cout<<"逆序栈输出:"<<endl;
while(!s1.empty())
{
cout<<s1.top()<<endl;
s1.pop();
}

}

void main()
{
stack<int> s1;
stack<int> s2;

ReverseOrder(s1,s2);

system("pause");
}


 

 


作者:xwdreamer