栈排序

编写程序,按升序对栈进行排序(即最大元素位于栈顶)。最多允许使用一个额外的栈存放临时数据,但不准将数据复制到别的数据结构(如数组)中。该栈支持如下操作:pop,push,peek / top,和isEmpty。

下面的代码直接使用C++ STL stack实现。

思路比较简单:每次都取主栈中相邻两元素进行比较,将其中较大元素放进子栈相应位置。

#include <bits/stdc++.h> // two stack to implement stackSort
using namespace std;

void insertStack(int val, stack<int>& hostStack, stack<int>& subStack) {
    if (!subStack.empty()) {
        int subTop = subStack.top();
        while (val > subTop) {
            hostStack.push(subTop);
            subStack.pop();
            if (subStack.empty()) {
                break;
            }
            subTop = subStack.top();
        }
    }
    subStack.push(val);
}

void stackSort(stack<int>& hostStack) {
    stack<int> subStack;
    while (!hostStack.empty()) {
        int front = hostStack.top();
        hostStack.pop();
        if (hostStack.empty()) {
            hostStack.push(front);
            break;
        }
        int next = hostStack.top();
        if (front >= next) {
            insertStack(front, hostStack, subStack);
        } else {
            hostStack.pop();
            insertStack(next, hostStack, subStack);
            hostStack.push(front);
        }
    }
    while (!subStack.empty()) {
        hostStack.push(subStack.top());
        subStack.pop();
    }
}

int main(int argc, char const *argv[]) {
    stack<int> hostStack;
    int n;
    cout << "how many elements to push into hostStack : \n";
    cin >> n;
    while (n--) {
        int tmp;
        cin >> tmp;
        hostStack.push(tmp);
    }
    stackSort(hostStack);
    cout << "after sort : \n";
    while (!hostStack.empty()) {
        cout << hostStack.top() << " ";
        hostStack.pop();
    }
    cout << endl;
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值