Sort An Unsorted Stack
Given a stack of integers, sort it in ascending order using another temporary stack.
Examples:
Input : [34, 3, 31, 98, 92, 23] Output : [3, 23, 31, 34, 92, 98] Input : [3, 5, 1, 4, 2, 8] Output : [1, 2, 3, 4, 5, 8]
经典题,这道题的套路是创建一个temp stack 用于元素的存取
public Stack<Integer> sortstack(Stack<Integer> input){ if(input == null){ return null; } Stack<Integer> tempStack = new Stack<>(); while(!input.isEmpty()){ int temp = input.pop(); while(!tempStack.isEmpty() && tempStack.peek() > temp){ input.push(tempStack.pop()); } tempStack.push(temp); } return tempStack; }
posted on 2018-05-17 09:22 IncredibleThings 阅读(130) 评论(0) 收藏 举报
浙公网安备 33010602011771号