Write a program to sort a stack in ascending order

前端 未结 4 598
天涯浪人
天涯浪人 2021-01-17 06:48

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 i

4条回答
  •  时光说笑
    2021-01-17 07:30

    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 stack = new Stack();
    
            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 sort(Stack stack) {
    
            if (stack.isEmpty()) {
                return null;
            }
    
            Stack sortedStack = new Stack();
    
            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;
        }
    }
    

提交回复
热议问题