Odd/Even logic with loop counter - Works out for most languages.


  • 0
    S
    // May be looks bit lengthy but different approach. Iterate list with current node with a loop counter. 
    // If loop counter is even then add current node to evenlist otherwise add to oddlist.
    public ListNode OddEvenList(ListNode head) 
    {
        if(head == null || head.next == null)
            return head;
    
        ListNode currNode = head; 
        ListNode oddList  = currNode;
        ListNode evenList = currNode.next;
        ListNode evenHead = evenList;
        
        currNode = currNode.next.next;
        
        int lpCnt = 3;
        
        while(currNode != null)
        {
            if(lpCnt % 2 == 0)
            {
               evenList.next = currNode;
               evenList = evenList.next;
            }
            else
            {
               oddList.next = currNode;
               oddList = oddList.next;
            }
            
            currNode = currNode.next;
            ++lpCnt;
        }
    
        if (evenList != null)
            evenList.next = null;
    
        if(oddList != null)
            oddList.next = evenHead;
            
        return head;   
    }

Log in to reply
 

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