天天看点

关于栈的几个操作

public static void main(String[] args) {
		Stack<Integer> stack = new Stack<>();
		stack.push(1);
		stack.push(2);
		stack.push(3);
		stack.push(4);
		stack.push(5);

		System.out.println(stack);
		System.out.println(stack.peek());
		/*int i = getAndRemoveLastElement(stack);
		System.out.println(i);*/

		/*reverse(stack);
		System.out.println(stack);*/

		sortStack(stack);
		System.out.println(stack);
		System.out.println(stack.peek());

	}

	/**
	 * 获取并移除栈底元素
	 */
	public static int getAndRemoveLastElement(Stack<Integer> stack) {
		int result = stack.pop();
		if (stack.empty()) {
			return result;
		} else {
			int last = getAndRemoveLastElement(stack);
			stack.push(result);
			return last;
		}
	}

	/**
	 * 反转栈
	 */
	public static void reverse(Stack<Integer> stack) {
		if (stack.empty()) {
			return;
		}
		int last = getAndRemoveLastElement(stack);
		reverse(stack);
		stack.push(last);

	}

	/**
	 * 将给定的栈排序
	 */
	public static void sortStack(Stack<Integer> stack) {
		Stack<Integer> help = new Stack<>();
		while (!stack.empty()) {
			int cur = stack.pop();
			while (!help.empty() && help.peek() > cur) {
				stack.push(help.pop());
			}
			help.push(cur);
		}
		while(!help.empty()){
			int t= help.pop();
			stack.push(t);
		}
	}