栈内元素排序

分别是利用一个辅助栈和两个辅助栈

public class StackSort {
	public static void sortWithOneCache(Stack stack) {
		if (stack == null || stack.isEmpty()) {
			return;
		}
		Stack cache = new Stack();

		while (!stack.isEmpty()) {
			int tmp = stack.pop();
			while (!cache.isEmpty() && tmp < cache.peek()) {
				stack.push(cache.pop());
			}
			cache.push(tmp);
		}

		while (!cache.isEmpty()) {
			stack.push(cache.pop());
		}
	}

	public static void sortWithTwoCache(Stack stack) {
		if (stack == null || stack.isEmpty()) {
			return;
		}
		Stack cache1 = new Stack();
		Stack cache2 = new Stack();

		while (!stack.isEmpty()) {
			int tmp = stack.pop();
			while (!cache1.isEmpty() && tmp < cache1.peek()) {
				cache2.push(cache1.pop());
			}
			cache1.push(tmp);
			while (!cache2.isEmpty()) {
				cache1.push(cache2.pop());
			}
		}

		while (!cache1.isEmpty()) {
			stack.push(cache1.pop());
		}
	}
}

 

 

你可能感兴趣的:(每日一题)