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; } };