Why My code is memory limit exceeded?


  • 0
    E

    The following code is memory limit exceeded for [1,2,3], but if I set curr.next = null with the comment code, it is accepted.
    please help me out, thank you.

        public ListNode oddEvenList(ListNode head) {
            if (head == null) return null;
            ListNode odd = new ListNode(1);
            ListNode oddtail = odd;
            ListNode even = new ListNode(0);
            ListNode eventail = even;
            ListNode curr = head;
            int i = 1;
            ListNode temp = null;
            while (curr != null) {
                if (i % 2 == 0) {
                    //temp = curr.next;
                    //curr.next = null;
                    eventail.next = curr;
                    eventail = curr;
                } else {
                   // temp = curr.next;
                    //curr.next = null;
                   oddtail.next = curr; 
                   oddtail = curr;
                }
                i++;
                //curr = temp;
                curr = curr.next;
            }
            oddtail.next = even.next;
            return odd.next;            
        }
    

  • 0
    S

    @Evan100, Not sure you got it fixed but I'm just guessing from your code the mistake would be you "forgot to increment current node twice before while loop".

    As you assigned first current node to oddlist and second one to evenlist, so you have to skip these from current node. and your while loops should start from 3rd node.
    Hope this helps.


  • 1
    J

    you need to set oddtail.next = eventail.next = null otherwise there will be a loop/circle in your linkedlist


Log in to reply
 

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