Given a singly linked list, group all odd nodes together followed by the even nodes. Please note here we are talking about the node number and not the value in the nodes.
You should try to do it in place. The program should run in O(1) space complexity and O(nodes) time complexity.
- The relative order inside both the even and odd groups should remain as it was in the input.
- The first node is considered odd, the second node even and so on …
Create an odd list and an even list, then combine together.
# Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: def oddEvenList(self, head: ListNode) -> ListNode: dummy = ListNode(0) odd_dummy = ListNode(0) even_dummy = ListNode(0) dummy.next = head count = 1 current = head odd = odd_dummy even = even_dummy while current != None: if count % 2 == 0: if count == 2: even_dummy.next = current even.next = current even = even.next else: if count == 1: odd_dummy.next = current odd.next = current odd = odd.next current = current.next count += 1 even.next = None odd.next = even_dummy.next dummy.next = odd_dummy.next return dummy.next
- Time complexity: O(N).
- Space complexity: O(1).