Segregate odd and even nodes in LL

Linked-List Logic Building Medium

Given the head of a singly linked list. Group all the nodes with odd indices followed by all the nodes with even indices and return the reordered list.


Consider the 1st node to have index 1 and so on. The relative order of the elements inside the odd and even group must remain the same as the given input.

Examples:

Input: head -> 1 -> 2 -> 3 -> 4 -> 5

Output: head -> 1 -> 3 -> 5 -> 2 -> 4

Explanation: The nodes with odd indices are 1, 3, 5 and the ones with even indices are 2, 4.

Input: head -> 4 -> 3 -> 2 -> 1

Output: head -> 4 -> 2 -> 3 -> 1

Explanation: The nodes with odd indices are 4, 2 and the ones with even indices are 3, 1.

Input: head -> 1

Constraints

  • 0 <= number of nodes in the Linked List <= 105
  • 0 <= ListNode.val <= 104

Hints

  • A brute-force approach would require scanning the list, separating odd/even indices into two lists, and merging them back. However, this results in O(n) space, which is inefficient.
  • Maintain Two Pointers, odd_head for odd-indexed nodes. even_head for even-indexed nodes. odd pointer moves by odd.next = even.next. even pointer moves by even.next = odd.next. Merge Both Groups, Once traversal ends, link the last odd node to even_head.

Company Tags

Swiggy Western Digital Lyft HashiCorp Byju's Ernst & Young Zynga PayPal Medtronic Philips Healthcare Optum JPMorgan Chase Oracle Reddit NVIDIA OYO Rooms Teladoc Health Epic Games Square Cloudflare DoorDash Morgan Stanley Roblox ARM Rockstar Games Google Microsoft Amazon Meta Apple Netflix Adobe