用一个栈实现另一个栈的排序(C++实现)

要求:

一个栈中的类型为整型,现在想将该栈从顶到底按从大到小的循序排序,只许申请一个栈。除此之外,可以申请新的变量,但不能申请额外的数据结构。

代码:

#include <iostream>
#include <stack>
using namespace std;
void sortStack(stack<int> &sta)
{
    stack<int> sta_1;
    while(!sta.empty()){
    int tem = sta.top();
    sta.pop();
    while(!sta_1.empty()&&sta_1.top()<tem){
      sta.push(sta_1.top());
      sta_1.pop();
    }
    sta_1.push(tem);
  }
    while(!sta_1.empty()){
      sta.push(sta_1.top());
      sta_1.pop();
    }
  }
int main()
{
    int a[] = {2,3,5,7,2};
    stack<int> sta;
    int i;
    for(i=0;i<5;i++)
    {
        sta.push(a[i]);
    }
    cout << "the stack before sorting are:" << endl;
    for(i=0;i<5;i++)
    {
        cout << sta.top() << endl;
        sta.pop();
    }
    for(i=0;i<5;i++)
    {
        sta.push(a[i]);
    }
    cout << "the stack after sorting are:" << endl;
    sortStack(sta);
    for(i=0;i<5;i++)
    {
        cout << sta.top() << endl;
        sta.pop();
    }
    return 0;
}
 
测试结果:
 
原文地址:https://www.cnblogs.com/shiheyuanfang/p/13417065.html