Can somebody tell me why my extremely short code does not pass memory limit


  • 0
    O
    public class Solution {
        public ListNode oddEvenList(ListNode head) {
            if (head==null) return null;
            if (head.next==null) return head;
            ListNode i=head.next.next, prev=head, evenHead=head.next;
            
            while (i!=null) {
                if (i.next!=null) prev.next.next=i.next;
                prev.next=i;
                prev=i;
                if (i.next!=null) i=i.next.next; else break; 
            }
            
            prev.next=evenHead;
            return head;
            
        }
    }

  • 0
    O

    cannot pass [1,2,3,4,5] but can pass [1,2,3,4,5,6,7,8]


  • 0
    O

    00000000000000000000000000


  • 0
    O

    Here's correct one, had some bug for odd-tailed queue

    public ListNode oddEvenList(ListNode head) {
            if (head==null) return null;
            if (head.next==null) return head;
            ListNode i=head.next.next, prev=head, evenHead=head.next;
    
            while (i!=null) {
                prev.next.next=i.next;
                prev.next=i;
                prev=i;
                if (i.next!=null) i=i.next.next; else break; 
            }
    
            prev.next=evenHead;
            return head;
    
        }

Log in to reply
 

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