Why "Memory Limit Exceeded "?


  • 0
    O
    public ListNode reverseList(ListNode head) {
        if (head == null) return null;
    
        ListNode curr = head;
        ListNode prev = curr;
        ListNode after = curr.next;
    
        while(after != null) { // I don't see any infinite loop because "after"
                                 //is alwasy curr.next or null;
            curr = after;
            after = curr.next;
            curr.next = prev;  //reverse
            prev = curr;
        }
        return curr;
    }

  • 0
    R

    you need to set the next of first node(which is your head.next) to null, otherwise the check statement they use will print forever, because your first node point back the second node

    public static  ListNode reverseList2(ListNode head) {
    ListNode pre = head;
    ListNode cur = head.next;
    head.next = null;
    ListNode nex = null;
    while( cur != null){
            nex = cur.next;
            cur.next = pre;
            pre = cur;
            cur = nex;
    }
    return pre;
    

    }


Log in to reply
 

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