Write a program to sort a stack in ascending order

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

    /** 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 temp = new Stack();
    
        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 ) );
        }
    
    }
    

提交回复
热议问题