EASIEST understand but POOREST spacing complexity method by using Stack


  • 0
    Y
    public ListNode reverseList(ListNode head) {
             if (head == null) {
                 return null;
             }
             Stack<Integer> s = new Stack<>();
             while (head.next != null) {
                 s.push(head.val);
                 head = head.next;
             }
             ListNode theNewHead = head;
             while (!s.empty()) {
                 ListNode newOne = new ListNode(s.pop());
                 head.next = newOne;
                 head = newOne;
             }
             return theNewHead;
    }
    

    Record the values through the next() method till reach the ''new head''.
    Record the new head and construct new ListNode next to ''new head'' till the stack is empty, then return the ''new head''.
    Just a lazy method for easy understanding.


Log in to reply
 

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