用一个栈实现另一个栈的排序

问题描述

    一个栈中元素的类型为整型,现在想将该栈从顶到底按从大到小的顺序排序,只许申请一个栈。除此之外,可以申请新的变量,但不能申请额外的数据结构。 

解答

    将要排序的栈记为stack,申请的辅助栈记为help,在stack上执行pop操作,弹出的元素记为cur。

  •     如果cur小于或者等于help的栈顶元素,则将cur直接压入help;
  •     如果cur大于help的栈顶元素,则将help的元素逐一弹出,逐一压入到stack,直到cur小于或者等于help的栈顶元素,再将cur压入help。

    一直执行以上操作,直到stack中的元素全部压入到help中。最后将help中的元素逐一压入到stack中,完成排序。

public static void sortStackByStack(Stack<Integer> stack) {
	 Stack<Integer> help = new Stack<Integer>();
	 while(!stack.isEmpty()) {
		 int cur = stack.pop();
		 while(!help.isEmpty()&&help.peek()>cur) {
			 stack.push(help.pop());
		 }
		 help.push(cur);
	 }
	 while(help.isEmpty()) {
		 stack.push(help.pop());
	 }
 }


猜你喜欢

转载自blog.csdn.net/xxxxxwwwwww/article/details/80052560