Memory exceed java?


  • -1
    N
    /**
    
    • Definition for singly-linked list.

    • public class ListNode {

    • int val;
      
    • ListNode next;
      
    • ListNode(int x) { val = x; }
      
    • }
      */
      public class Solution {
      public ListNode oddEvenList(ListNode head) {
      if (head == null || head.next == null)
      return head;
      ListNode even_head = head.next;
      ListNode odd = head, even = even_head;
      while (even != null && even.next != null) {
      odd.next = even.next;
      even.next = odd.next;
      odd = odd.next;
      even = even.next;
      }
      odd.next = even_head;
      return head;

      }
      }


  • 0
    J
    • either: change "even.next = odd.next" to "even.next = odd.next.next"
    • or: move odd=odd.next one line up before "even.next = odd.next"

    Assume: 1->2->3->4, when odd = 1 and even = 2,

    Your original code:

    1. odd.next = even.next // 1.next = 3; Note that you haven't moved odd
      yet. so odd is still 1
    2. even.next = odd.next // 2.next = 3; Wrong! this is actually a no-op. You want to set 2.next = 4

    // At this point, the list look like: 1->3->4 and 2->3->4, which is wrong and eventually cause a loop in your result list .

    Memory limit is just because infinite loop caused by this when verifying a test case.


Log in to reply
 

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