栈和队列 用一个栈实现另一个栈的排序

题目要求是不能申请额外的数据结构。

其中,stack是要被排序的栈,help是辅助栈,cur是从stack弹出的试图压入help的栈元素。

思路总结:

if cur < help.peek(),help.push(cur). 

else stack.push(help.pop()). 直到cur < help.peek().

收获:

栈遍历的方式有集合与栈弹出。其中集合的方式是从栈底到栈顶依次遍历。

import java.util.Stack;

public class Main {

    public static void SortStack(Stack<Integer> stack) {
        Stack<Integer> help = new Stack<Integer>();

        while (!stack.isEmpty()) {
            int cur = stack.pop();
            while (!help.isEmpty() && (cur > help.peek())) {
                stack.push(help.pop());
            }
            help.push(cur);
        }

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

    public static void main(String[] args) {
        Stack<Integer> stack = new Stack<Integer>();
        Integer[] a = {5, 3, 4, 2, 1};
        for (int i : a){
        //for(int i = 0; i < a.length; i++) {
            stack.add(i);
            System.out.println(stack.peek());
        }

        System.out.println("===========");

        SortStack(stack);

        for(Integer x : stack) {
            System.out.println(x);
        }//集合遍历方式是从栈底往栈顶
        System.out.println("===========");
        while (!stack.isEmpty()) {
            System.out.println(stack.pop());
        }

    }

}

猜你喜欢

转载自blog.csdn.net/rivalak/article/details/81068199