每日一题 为了工作 2020 0307 第五题

/**
* 题目: 用一个栈实现另一个栈的排序
* 一个栈的元素是整形,现在想将该栈从顶到底按从大到小的顺序排序,只许申请一个栈。
* 除此之外,可以申请新的变量,但不能申请额外的数据结构。
* 分析:
* 将要排序的栈记为stack,申请的辅助栈记为helpStack。在stack栈上执行pop
* 操作,弹出的元素记为cur。
*
* 1.如果cur小于或等于helpStack的栈顶元素,则将cur直接压入栈中。
* 2.如果cur大禹helpStack的栈顶元素,则将helpStack的元素逐一弹出,逐一
* 压入stack内,直到cur小于或等于helpStack的栈顶元素,再将cur压入栈内。
* @author 雪瞳
*
*/

* 代码

import java.util.Stack;

public class sortStackByStack {
    
    public static Stack<Integer> sort(Stack<Integer> stack, Stack<Integer> helpStack) {
        
        
        //排序直到stack内没有元素
        while(!stack.isEmpty()) {
            int cur = stack.pop();
            //若helpStack栈不为空且栈顶元素大于cur,则直接将helpStack的栈顶元素弹出压入栈stack内
            while(!helpStack.isEmpty() && helpStack.peek()<cur) {
                stack.push(helpStack.pop());
            }
            helpStack.push(cur);
        }
        //最终排序的结果要存储于stack内 反序压入即可实现由大到小排序
        while(!helpStack.isEmpty()) {
            stack.push(helpStack.pop());
        }
        return stack;
    }
    public void showPrint(Stack<Integer> stack) {
        System.out.println("\n栈顶到栈底的元素依次是...");
        while(!stack.isEmpty()) {
            System.out.print(stack.pop()+"\t");
        }
    }
    public static Stack<Integer> showStack(Stack<Integer> stack) {
         Stack<Integer> helpStack = new Stack<>();
         while(!stack.isEmpty()) {
             int trans = stack.pop();
             System.out.print(trans+"\t");
             helpStack.push(trans);
         }
         while(!helpStack.isEmpty()) {
             stack.push(helpStack.pop());
         }
         return stack;
    }
}
public class testSort {
    public static void main(String[] args) {
        sortStackByStack test = new sortStackByStack();
        Stack<Integer> stack = new Stack<>();
        Stack<Integer> helpStack = new Stack<>();
        Random rand = new Random();
        int count = 0;
        
        while(count<10) {
            stack.push(rand.nextInt(10));
            count++;
        }
        System.out.println("栈顶到栈底的元素依次是...");
        stack = test.showStack(stack);
        stack = test.sort(stack, helpStack);
        test.showPrint(stack);
    }
}

* 运行结果

 

posted @ 2020-03-07 13:20  雪瞳  阅读(156)  评论(0编辑  收藏  举报