2017-06-14 105 views
0

我在考慮使用臨時變量來保存從堆棧彈出的值,將它們添加到隊列中,然後從隊列中刪除值並將它們推送到堆棧直到它被排序,但是這並不是真的有效。另外,除了堆棧和隊列操作之外,不允許其他數據結構。嘗試使用隊列以降序對堆棧進行排序

+0

歡迎計算器!請花些時間閱讀[幫助頁面](http://stackoverflow.com/help),尤其是名爲[「我可以問些什麼話題?」]的章節(http://stackoverflow.com/help/)討論話題)和[「我應該避免問什麼類型的問題?」](http://stackoverflow.com/help/dont-ask)。請參閱[tour](http://stackoverflow.com/tour)並閱讀[如何提出良好問題](http://stackoverflow.com/help/how-to-ask)。最後,請學習如何創建[最小,完整和可驗證示例](http://stackoverflow.com/help/mcve)。 – Markus

回答

0

使用此僞代碼進行排序堆問,如果任何混亂

sort(Stack S) 
{ 
    if (S is not empty) 
    { 
     // Pop the top element off the stack 
     int t = S.pop(); 
     //Sort the remaining stack recursively 
     Sort(s) 
     //Push the top element back into the sorted stack 
     insert(S, t) 
    } 
} 

insert(Stack S, int t) { 
    if (S.isEmpty()) 
     S.push(t); 
    else if (t > S.top()) 
     // t is at its position in sorted stack 
     S.push(t); 
    else { 
     int u = S.pop(); 
     insert(S, t); 
     S.push(u); 
    } 
} 
相關問題