Sort using 2 stacks


  • 0
    A

    Re: [Given a stack](sort it in non-decreasing order)

    public Stack<Integer> sortStack (Stack<Integer> s) {
    Stack<Integer> result = new Stack<Integer>();
    while(!s.isEmpty()) {
    int temp = s.pop();
    while(!result.isEmpty() && result.peek() > temp)
    s.push(result.pop());
    result.push(temp);
    }
    }

    while(!result.isEmpty())
    s.push(result.pop());

    return s;
    }


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.