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

要求:

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

解题思路:

     待排序的栈stack, 辅助栈help。 在stack上执行pop操作,记元素为cur

     if cur <= 【help 的栈顶元素】,cur 压入help栈中;

     else cur > 【help 的栈顶元素】,逐一弹出help, 直到cur <= 【help 的栈顶元素】,在将cur压入help

      一直执行以上操作,直到stack中的全部元素都导入help栈中,(此时从栈顶到栈底:有小到大),最后,将help栈中的元素,pop一下,排序

import java.util.Stack;

public class Problem05_StackSortStack {
    /*
     * 待排序的栈stack, 辅助栈help。 在stack上执行pop操作,记元素为cur
            if cur <= 【help 的栈顶元素】,cur 压入help栈中;
            else cur > 【help 的栈顶元素】,逐一弹出help, 直到cur <= 【help 的栈顶元素】,在将cur压入help
      一直执行以上操作,直到stack中的全部元素都导入help栈中,(此时从栈顶到栈底:有小到大),最后,将help栈中的元素,pop一下,排序
     */
    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());
        }
    }
    

    public static void main(String[] args) {
        Stack<Integer> stack = new Stack<Integer>();
        stack.push(3);
        stack.push(1);
        stack.push(6);
        stack.push(2);
        stack.push(5);
        stack.push(4);
        sortStackByStack(stack);        
        int stack_size= stack.size();
        System.out.println("stack元素是:");
        for (int size=0; size < stack_size; size ++){            
            System.out.println(stack.pop());
        }
        
        
    }

}

执行结果:

stack元素是:
6
5
4
3
2
1
posted @ 2017-05-09 15:32  蒋励  阅读(768)  评论(0编辑  收藏  举报