/* 思路:棧1(5 — 8 - 3 - 1) 棧2(7 - 6) 第一步 拿出5 棧1(8 3 1) 棧2(7 6) 第二步 那5和棧2裏面的數比較大於5的pop出來存入棧1,棧1(6 7 8 3 1) 棧2(5) 依次弄下去 直到棧1爲空 */ import java.util.*; public class Main { public static void main(String[] args) { System.out.println("Hello World!"); Stack<Integer> s = new Stack<>(); s.push(1); s.push(3); s.push(8); s.push(5); s.push(7); s.push(6); sortStack(s); System.out.println(s.pop()); System.out.println(s.pop()); System.out.println(s.pop()); System.out.println(s.pop()); System.out.println(s.pop()); System.out.println(s.pop()); } public static void sortStack(Stack<Integer> s) { Stack<Integer> resultStack = new Stack<>(); while(!s.isEmpty()) { int temp = s.pop(); if(resultStack.isEmpty() || resultStack.peek() <= temp) { resultStack.push(temp); } else { while(!resultStack.isEmpty() && resultStack.peek() > temp) { s.push(resultStack.pop()); } resultStack.push(temp); } } while(!resultStack.isEmpty()) { s.push(resultStack.pop()); } } }
Sort Stack java 走地牙 CTCI 3.5
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.