Write a program to sort a stack in ascending order

前端 未结 4 606
天涯浪人
天涯浪人 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:17

    public class ReverseStack {
    
        public static void main(String[] args) {
            Stack stack =new Stack();
            stack.add(3);stack.add(0);stack.add(2);stack.add(1);
            sortStack(stack);
            System.out.println(stack.toString());
        }
    
        public static void sortStack(Stack stack){
    
             int tempElement=stack.pop();
             if(!stack.isEmpty()){
                 sortStack(stack);
             }
             insertStack(stack,tempElement);
        }
    
        private static void insertStack(Stack stack, int element) {
            if(stack.isEmpty()){
                stack.push(element);
                return;
            }
            int temp=stack.pop();
    
            //********* For sorting in ascending order********
            if(element

提交回复
热议问题