SortStack By Stack

#include <iostream>
#include <stack>
#include <cstdlib>
using namespace std;

void sortStackByStack(stack<int>& stackk){
    stack<int> help;
    while (!stackk.empty()) {
        int cur = stackk.top();
        stackk.pop();
        while (!help.empty() && help.top() > cur) {
            stackk.push(help.top());
            help.pop();
        }
        help.push(cur);
    }
    while (!help.empty()) {
        stackk.push(help.top());
        help.pop();
    }
}
int main() {
    stack<int> test;

    for (int i = 0; i < 8; i++) {
        test.push(rand() % 50);
    }

    sortStackByStack(test);

    for (int i = 0; i < 8; i++) {
        cout << test.top() << " ";
        test.pop();
    }
    cout << endl;

    return 0;
}

将要排序的栈记为stack,申请的辅助栈记为help。在stack.上执行pop操作,弹出的元素记为cur。

  • 如果cur小于或等于help的栈顶元素,则将cur直接压入help;
  • 如果cur大于help的栈顶元素,则将help的元素逐一弹出,逐一压入stack,直到cur小于或等于help的栈顶元素,再将cur压入help。

一直执行以上操作,直到stack中的全部元素都压入到help。最后将help中的所有元素逐一压入stack,即完成排序。

posted @ 2019-07-28 15:44  木子石页  阅读(188)  评论(0编辑  收藏  举报