cpp concise solution.


  • 0
    class Solution {
    public:
      ListNode* oddEvenList(ListNode* head) {
        if (head == NULL)
        {
          return head;
        }
    
        ListNode *odd = head;
        ListNode *even = head -> next;
        ListNode *evenHead = even;
    
        while (even != NULL && even -> next != NULL)
        {
          ListNode *nextOdd = odd -> next -> next;
          ListNode *nextEven = even -> next -> next;
          odd -> next = nextOdd;
          even -> next = nextEven;
          odd = nextOdd;
          even = nextEven;
        }
    
        odd -> next = evenHead;
        
        return head;
      }
    };
    

  • 0
    E

    There's no need to create extra variable in your loop, you can write it as this:

    while(even && even->next){
        odd->next = odd->next->next;
        even->next = even->next->next;
        odd = odd->next;
        even = even->next;
     }
    

Log in to reply
 

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