← Back to companies
[ OK ] Loaded —
[ INFO ]
$ cd
$ ls -lt
01
02
03
04
05
$ ls -lt
01
02
03
04
05
user@intervues:~/$
Given the head of a singly linked list, group all nodes at odd indices together followed by the nodes at even indices, and return the reordered list. The first node is considered odd, the second node is even, and so on. Preserve the relative order within both groups.
Example 1:
Example 2:
[0, 30].0 <= Node.val <= 100To solve this problem, you can follow these steps:
odd and even, to represent the head of the odd and even linked lists, respectively.oddPtr and evenPtr, to traverse the original linked list.curr, to traverse the original linked list starting from the head.odd list and move oddPtr to the next node.even list and move evenPtr to the next node.even list to the end of the odd list.odd list.Here's a Python code snippet to illustrate the solution:
`python class Solution: def oddEvenList(self, head: ListNode) -> ListNode: if not head: return head
odd = ListNode(0)
even = ListNode(0)
oddPtr, evenPtr = odd, even
curr = head
index = 1
while curr:
if index % 2 == 1:
oddPtr.next = curr
oddPtr = oddPtr.next
else:
evenPtr.next = curr
evenPtr = evenPtr.next
curr = curr.next
index += 1
evenPtr.next = None
oddPtr.next = even.next
return odd.next
`
This solution has a time complexity of O(n) and a space complexity of O(1), where n is the number of nodes in the linked list.