Sharing my C# solution with even, odd list


  • 0
    Y
    /*
    

    the main idea will be create two link list, one for even point, one for odd point.

    */
    
    
    
    
    /**
     * Definition for singly-linked list.
     * public class ListNode {
     *     public int val;
     *     public ListNode next;
     *     public ListNode(int x) { val = x; }
     * }
     */
    public class Solution {
        public ListNode OddEvenList(ListNode head) {
            
            //use two link list, one for even, one for odd
            
            var evenHead=new ListNode(0);
            var newHead=evenHead;
            var oddHead=new ListNode(0);
            var newOddHead=oddHead;
            
            var isEven=true;
            while(head!=null)
            {
                var tempNext = head.next;
                head.next=null;
                if(isEven)
                {
                     evenHead.next=head;
                     evenHead=evenHead.next;
                }
                else
                {
                    oddHead.next=head;
                    oddHead=oddHead.next;
                }
                
                isEven=!isEven;
                head=tempNext;
            }
            
            evenHead.next=newOddHead.next;
            
            return newHead.next;
            
        }
    }

Log in to reply
 

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