要求:將一個棧按從頂到底,從大到小的順序排序,只許額外申請一個棧來操作
思路:如果stack,pop出來的元素比help棧頂小,直接壓入。否則,help棧不斷彈出元素,直到找到合適的地方再壓入。
總結:善於總結操作,不要每個情況都寫一個if操作,看看內部的操作是不是都一樣,一樣的話可以提出來一起寫。
public static void sortStack(Stack<Integer> stack) {
Stack<Integer> help = new Stack<Integer>();
while(!stack.isEmpty()) {
int temp = stack.pop();
while(!help.isEmpty()&&help.peek()<temp) { //只有當pop出來的元素值比help棧頂元素大,纔會將help中的元素移回stack
stack.push(help.pop());
}
help.push(temp); //其他不管是help爲空,還是pop出來的元素值比help棧頂小,都是一律push。所以合併寫一個就可以,不用再if寫情況了
}
while(!help.isEmpty()) { //最後將反序的help壓回stack,順序就對了
stack.push(help.pop());
}
}