Java 编写程序以升序对堆栈进行排序

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24768011/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-14 14:46:04  来源:igfitidea点击:

Write a program to sort a stack in ascending order

javasortingstack

提问by Jie

Can someone help look at my code, please? Thank you so much for your help. The input stack is [5, 2, 1, 9, 0, 10], my codes gave output stack [0, 9, 1, 2, 5, 10], 9 is not in the right position.

有人可以帮忙看看我的代码吗?非常感谢你的帮助。输入堆栈是 [5, 2, 1, 9, 0, 10],我的代码给出了输出堆栈 [0, 9, 1, 2, 5, 10], 9 不在正确的位置。

import java.util.*;

public class CC3_6 {
public static void main(String[] args) {
    int[] data = {5, 2, 1, 9, 0, 10};
    Stack<Integer> myStack = new Stack<Integer>();
    for (int i = 0; i < data.length; i++){
        myStack.push(data[i]);
    }
    System.out.println(sortStack(myStack));
}

public static Stack<Integer> sortStack(Stack<Integer> origin) {
    if (origin == null)
        return null;
    if (origin.size() < 2)
        return origin;

    Stack<Integer> result =  new Stack<Integer>();
    while (!origin.isEmpty()) {
        int smallest = origin.pop();
        int remainder = origin.size();
        for (int i = 0; i < remainder; i++) {
            int element = origin.pop();
            if (element < smallest) {
                origin.push(smallest);
                smallest = element;                    
            } else {
                origin.push(element);
            }
        }
        result.push(smallest);
    }
    return result;

}

}

}

回答by imvp

/** the basic idea is we go on popping one one element from the original
 * stack (s) and we compare it with the new stack (temp) if the popped
 * element from original stack is < the peek element from new stack temp
 * than we push the new stack element to original stack and recursively keep
 * calling till temp is not empty and than push the element at the right
 * place. else we push the element to the new stack temp if original element
 * popped is > than new temp stack. Entire logic is recursive.
 */
public void sortstk( Stack s )
{
    Stack<Integer> temp = new Stack<Integer>();

    while( !s.isEmpty() )
    {

        int s1 = (int) s.pop();

        while( !temp.isEmpty() && (temp.peek() > s1) )
        {
            s.push( temp.pop() );
        }
        temp.push( s1 );

    }

    // Print the entire sorted stack from temp stack
    for( int i = 0; i < temp.size(); i++ )
    {
        System.out.println( temp.elementAt( i ) );
    }

}

回答by Udit Nagi

public class ReverseStack {

    public static void main(String[] args) {
        Stack<Integer> stack =new Stack<Integer>();
        stack.add(3);stack.add(0);stack.add(2);stack.add(1);
        sortStack(stack);
        System.out.println(stack.toString());
    }

    public static void sortStack(Stack<Integer> stack){

         int tempElement=stack.pop();
         if(!stack.isEmpty()){
             sortStack(stack);
         }
         insertStack(stack,tempElement);
    }

    private static void insertStack(Stack<Integer> stack, int element) {
        if(stack.isEmpty()){
            stack.push(element);
            return;
        }
        int temp=stack.pop();

        //********* For sorting in ascending order********
        if(element<temp){
            insertStack(stack,element);
            stack.push(temp);
        }else{
            stack.push(temp);
            stack.push(element);
        }
        return;
    }

}

回答by Niraj Kumar

Here's my version of the code which is pretty straightforward to follow.

这是我的代码版本,非常易于遵循。

import java.util.Stack;

public class StackSorting {

    public static void main(String[] args) {
        Stack<Integer> stack = new Stack<Integer>();

        stack.push(12);
        stack.push(100);
        stack.push(13);
        stack.push(50);
        stack.push(4);

        System.out.println("Elements on stack before sorting: "+ stack.toString());

        stack = sort(stack);

        System.out.println("Elements on stack after sorting: "+ stack.toString());

    }

    private static Stack<Integer> sort(Stack<Integer> stack) {

        if (stack.isEmpty()) {
            return null;
        }

        Stack<Integer> sortedStack = new Stack<Integer>();

        int element = 0;
        while(!stack.isEmpty()) {
            if (stack.peek() <= (element = stack.pop())) {
                if (sortedStack.isEmpty()) {
                    sortedStack.push(element);
                } else {
                    while((!sortedStack.isEmpty()) && sortedStack.peek() > element) {
                        stack.push(sortedStack.pop());
                    }
                    sortedStack.push(element);
                }
            }
        }

        return sortedStack;
    }
}

回答by Aalekh Patel

package TwoStackSort;
import java.util.Random;
import java.util.Stack;

public class TwoStackSort {
    /**
     *
     * @param stack1 The stack in which the maximum number is to be found.
     * @param stack2 An auxiliary stack to help.
     * @return The maximum integer in that stack.
     */
    private static Integer MaxInStack(Stack<Integer> stack1, Stack<Integer> stack2){
        if(!stack1.empty()) {
            int n = stack1.size();
            int a = stack1.pop();
            for (int i = 0; i < n-1; i++) {
                if(a <= stack1.peek()){
                    stack2.push(a);
                    a = stack1.pop();
                }
                else {
                    stack2.push(stack1.pop());
                }
            }
            return a;
        }
        return -1;
    }

    /**
     *
     * @param stack1 The original stack.
     * @param stack2 The auxiliary stack.
     * @param n An auxiliary parameter to keep a record of the levels of recursion.
     */
    private static void StackSort(Stack<Integer> stack1, Stack<Integer> stack2, int n){
        if(n==0){
            return;
        }
        else{
            int maxinS1 = MaxInStack(stack1, stack2);
            StackSort(stack2, stack1, n-1);
            if(n%2==0){
                stack2.push(maxinS1);
            }
            else{stack1.push(maxinS1);}
        }
    }
    /**
     *
      * @param stack1 The original stack that needs to be sorted.
     * @param stack2 The auxiliary stack.
     * @return The descendingly sorted stack.
     */
    public static Stack<Integer> TwoStackSorter(Stack<Integer> stack1, Stack<Integer> stack2){
        StackSort(stack1, stack2, stack1.size()+stack2.size());
        return (stack1.empty())? stack2:stack1;
    }

    public static void main(String[] args) {
        Stack<Integer> stack = new Stack<>();
        Random random = new Random();
        for (int i = 0; i < 50; i++) {
            stack.push(random.nextInt(51));
        }
        System.out.println("The original stack is: ");
        System.out.print(stack);
        System.out.println("\n" + "\n");
        Stack<Integer> emptyStack = new Stack<>();
        Stack<Integer> res =  TwoStackSorter(stack, emptyStack);
        System.out.println("The sorted stack is: ");
        System.out.print(res);
    }
}

This is a code that I came up with yesterday night after an hour of brainstorming. When I was solving a version of this problem, I had a restriction that at most only one additional stack can be used. This is an intense recursive solution to this problem. I've used 2 private methods to get me the stuff that I required from the stack. I really love the way that recursion worked here. Basically the version that I was solving required to sort a stack in ascending/descending order by using at most one additional stack. Note that no other data structures should be used.

这是我昨天晚上经过一个小时的头脑风暴想出的代码。当我解决这个问题的一个版本时,我有一个限制,即最多只能使用一个额外的堆栈。这是这个问题的强烈递归解决方案。我使用了 2 个私有方法从堆栈中获取我需要的东西。我真的很喜欢递归在这里的工作方式。基本上,我正在解决的版本需要通过最多使用一个附加堆栈以升序/降序对堆栈进行排序。请注意,不应使用其他数据结构。