[CareerCup] 3.6 Sort Stack 棧排序


 

3.6 Write a program to sort a stack in ascending order (with biggest items on top). You may use at most one additional stack to hold items, but you may not copy the elements into any other data structure (such as an array). The stack supports the following operations: push, pop, peek, and isEmpty.

 

這道題讓我們對棧進行排序,棧頂放大的元素,而且限定了我們只能用一個輔助棧。那么我們的思路是,先取出給定棧的棧頂元素存入到一個臨時變量中,然后我們看輔助棧的棧頂元素是否大於取出的元素,大的話就把輔助棧的棧頂元素壓入給定棧中,直到輔助棧為空或是棧頂元素小於取出值,這時將取出值壓入輔助棧,然后繼續從給定棧中取值,以此類推直至給定棧取空,這時候輔助棧就是排序完成的結果,返回即可,參見代碼如下:

 

class Solution {
public:
    stack<int> sort(stack<int> s) {
        stack<int> res;
        while (!s.empty()) {
            int v = s.top(); s.pop();
            while (!res.empty() && res.top() > v) {
                s.push(res.top());
                res.pop();
            }
            res.push(v);
        }
        return res;
    }
};

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM