用一个栈排序另一个栈

题目:

    一个栈中的元素都是整型,现在想将改栈从栈顶到栈底从大到小排列,只允许申请一个栈,除此之外可以申请新的变量,但不能申请额外的数据结构。

思路:

    两个栈,一个记为stackData,一个记为stackSort。一个整型变量cur

    stackData弹栈到cur,判断stackSort是否为空

    如果为空,将cur压栈到stackSort。如果不为空判断cur是否小于等于stackSort栈顶元素

    如果小于,curr压栈到stackSort。

    否则将stackSort弹栈到stackData,直到cur小于等于stackSort栈顶元素或者stackSort为空,然后cur压栈

    当stackData为空时排序完成,将stackSort中元素逐一弹栈到stackData中

代码:

#include <stack>

using namespace std;


void sortStackByStack(stack<int>& stackData)
{
    stack<int> stackSort;

    while( !stackData.empty() )
    {
        int cur = stackData.top();
        stackData.pop();

        if( stackSort.empty() )
            stackSort.push(cur);
        else
        {
            if( cur <= stackSort.top() )
                stackSort.push(cur);
            else
            {
                int r;
                //此处必须先判断是否为空
                while( !stackSort.empty() && ( cur > (r = stackSort.top()) ) )
                {
                    stackSort.pop();
                    stackData.push(r);
                }
                stackSort.push(cur);
            }
        }
    }

    while( !stackSort.empty() )
    {
        stackData.push(stackSort.top());
        stackSort.pop();
    }
}

猜你喜欢

转载自blog.csdn.net/king_qg/article/details/80359608
今日推荐