用一個棧實現另一個棧的排序(java實現)
阿新 • • 發佈:2019-02-16
一、題目
一個棧中元素的型別為整形,現在想將該棧從頂到底按從大到小的順序排序,只許申請一個棧,除此之外,可以申請新的變數,但不能申請額外的資料結構。如何完成排序?
二、解答
將要排序的棧記為stack,申請的輔助棧記為help。在stack上執行pop操作,彈出的元素記為cur。
(1)如果cur小於或等於help的棧頂元素,則將cur直接壓入help;
(2)如果cur大禹help的棧頂元素,則將該help的元素注意彈出,逐一壓入stack棧,直到cur小魚或等於help的棧頂元素,再將 cur壓入help。
三、具體可執行程式碼如下:
import java.util.Stack; public class SortOfStack { public static void main(String[] args) { SortOfStack s = new SortOfStack(); Stack<Integer> stack = new Stack<Integer>(); stack.push(4); stack.push(3); stack.push(5); stack.push(1); System.out.println(stack); s.sortStackByStack(stack); System.out.println(stack); } public static void sortStackByStack(Stack<Integer> stack) { Stack<Integer> help = new Stack<Integer>(); while(!stack.isEmpty()) { int cur = stack.pop(); while(!help.isEmpty()&&help.peek()<cur) { stack.push(help.pop()); } help.push(cur); } while(!help.isEmpty()) { stack.push(help.pop()); } } }
四、執行結果截圖: