DEV Community

Cover image for Leetcode Odd Even Linked List - Solution & Video Explaination
shubhsheth
shubhsheth

Posted on

Leetcode Odd Even Linked List - Solution & Video Explaination

Solution

/* struct ListNode {
  int val;
  ListNode *next;
  ListNode() : val(0), next(nullptr) {}
  ListNode(int x) : val(x), next(nullptr) {}
  ListNode(int x, ListNode *next) : val(x), next(next) {}
}; */

ListNode* oddEvenList(ListNode* head) {
  if (head == nullptr) {
    return head;
  }

  ListNode* oddPointer = head;
  ListNode* evenHead = oddPointer->next;
  ListNode* evenPointer = evenHead;

  while(evenPointer != nullptr && evenPointer->next != nullptr) {
    oddPointer->next = evenPointer->next;
    oddPointer = oddPointer->next;
    evenPointer->next = oddPointer->next;
    evenPointer = evenPointer->next;
  }

  oddPointer->next = evenHead;
  return head;
}
Enter fullscreen mode Exit fullscreen mode

Complexity

Runtime: O(n)
Space: O(1)

Top comments (0)