Wrong test case [2,1,4,3,6,5,7,8], expected: [2,4,6,7,1,3,5,8]? C# solution


  • 0
    H
     * Definition for singly-linked list.
     * public class ListNode {
     *     public int val;
     *     public ListNode next;
     *     public ListNode(int x) { val = x; }
     * }
     */
    public class Solution {
        // Test case: 2,1,4,3,6,5,7,8
        // Output:[2,4,6,8,1,3,5,7]
        // Expected:[2,4,6,7,1,3,5,8]
        public ListNode OddEvenList(ListNode head) {
            ListNode current = head; // 2
            ListNode odd = null; 
            ListNode oddHead = null;
            ListNode even = null;
            ListNode evenHead = null;
            while(current != null){
                if(current.val % 2 == 1){
                    if(odd == null){   
                        odd = current;
                        oddHead = current;
                    }
                    else{
                        odd.next = current;
                        odd = odd.next;
                    }
                }
                else{
                    if(even == null){
                        even = current;
                        evenHead = even;
                    }
                    else{
                        even.next = current;
                        even = even.next;
                    }
                }          
                current = current.next;
            }
            
           
            if(oddHead != null && evenHead != null){
                if(head.val % 2 == 1)
                {
                    odd.next = evenHead;
                    even.next = null;
                }
                else
                {
                    even.next = oddHead;
                    odd.next = null;
                }
            }
            
            return head;
        }
    }
    

Log in to reply
 

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