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

546 阅读1分钟

实现思路

一、新建一个help栈,这个栈从大到小排列(从栈顶到栈底)。

二、遍历要排序的stack栈。

1、初始化help栈

2、从stack中pop数据(记为curr),和help中的栈顶数据进行比较

help的栈顶数据更小,可以直接将curr移动到help中去。
如果help的栈顶数据更大,则需要将help中大于curr的数据全部移动到stack中去。

public static void main(String args[]) {

    Stack<Integer> stack = new Stack<Integer>();
    stack.add(3);
    stack.add(1);
    stack.add(5);
    stack.add(2);
    stack.add(4);

    Stack<Integer> help = new Stack<Integer>();//help栈由大到小排列

    while (!stack.isEmpty()) {
      Integer curr = stack.pop();
      if (help.isEmpty()) {
        help.push(curr);
      } else {
        while (!help.isEmpty() && help.peek() > curr) {
          stack.push(help.pop());
        }
        help.push(curr);
      }

    }

    while (!help.isEmpty()) {
      System.out.println(help.pop());
    }
  }