用一个栈实现另一个栈的排序

【说明】:

  本文是左程云老师所著的《程序员面试代码指南》第一章中“用一个栈实现另一个栈的排序”这一题目的C++复现。

  本文只包含问题描述、C++代码的实现以及简单的思路,不包含解析说明,具体的问题解析请参考原书。

  感谢左程云老师的支持。

【题目】:

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

【思路】:

  不知到大家有木有玩过九连环,感觉解题思路相当类似;这个解法和插入排序也有一定的类似度。

【编译环境】:

  CentOS6.7(x86_64)

  gcc 4.4.7

【实现】:

  实现及测试代码

/*
 *文件名:sortStack.cpp
 *作者:
 *摘要:用一个栈实现另一个栈的逆序
 */

#include <stack>
#include <iostream>

using namespace std;

void sortStack(stack<int> &s)
{
    stack<int> auxS;
    while(!s.empty())
    {
        int tmp = s.top();
        s.pop();
        while(!auxS.empty() && auxS.top() < tmp)
        {
            s.push(auxS.top());
            auxS.pop();
        }
        auxS.push(tmp);
    }
    while(!auxS.empty())
    {
        s.push(auxS.top());
        auxS.pop();
    }
}

int main()
{
    int a[] = {3,4,5,1,2,1};
    stack<int> s;
    int i;
    for(i=0;i<6;i++)
    {
        s.push(a[i]);
    }
    cout << "The datum of the stack before sorting are:" << endl;
    for(i=0;i<6;i++)
    {
        cout << s.top() << endl;
        s.pop();
    }
    for(i=0;i<6;i++)
    {
        s.push(a[i]);
    }
    cout << "The datum of the stack after sorting are:" << endl;
    sortStack(s);
    for(i=0;i<6;i++)
    {
        cout << s.top() << endl;
        s.pop();
    }
    return 0;
}
View Code

注:

  转载请注明出处;

  转载请注明源思路来自于左程云老师的《程序员代码面试指南》。

原文地址:https://www.cnblogs.com/PrimeLife/p/5322057.html