zoukankan      html  css  js  c++  java
  • stack排序

    Cracking Interview 3-6

    用的书上的思路,O(n^2)的时间复杂度。

    #include <iostream>
    #include <stack>
    using namespace std;
    
    stack<int> sort(stack<int> unorderStack)
    {
        stack<int> orderStack;
        stack<int> tmpStack;
    
        while(!unorderStack.empty())
        {
            int value = unorderStack.top();
            if (orderStack.empty())
                orderStack.push(value);
            else if (value < orderStack.top())
                orderStack.push(value);
            else {
                while (!orderStack.empty() && value > orderStack.top()){
                    tmpStack.push(orderStack.top());
                    orderStack.pop();
                }
                orderStack.push(value);
                while (!tmpStack.empty()){
                    orderStack.push(tmpStack.top());
                    tmpStack.pop();
                }
            }
            unorderStack.pop();
        }
        return orderStack;
    }
    
    int main()
    {
        stack<int> stk;
        for (int i = 0; i < 10; i++)
        {
            int value = rand()%150;
            cout<<"Pushing : "<<value<<endl;
            stk.push(value);
        }
        cout<<"sorting ..."<<endl;
        stk = sort(stk);
        cout<<"sort complete"<<endl;
        while (!stk.empty())
        {
            cout<<stk.top()<<endl;
            stk.pop();
        }
        return 0;
    }

    EOF

  • 相关阅读:
    hdu 2546 饭卡
    poj 2262 Goldbach's Conjecture
    poj 1287 Networking
    poj 2377 Bad Cowtractors
    poj 1789 Truck History
    poj 2349 Arctic Network
    poj 1258 Agri-Net
    acdream 20140730 D题
    hdu 1012 素数判定
    hdu 2098 分拆素数和
  • 原文地址:https://www.cnblogs.com/lihaozy/p/2809866.html
Copyright © 2011-2022 走看看