Code-Memo

Reorder List

Given a singly linked list head, reorder it to alternate the nodes from the first half and the second half of the list.

Approach

  1. Find the Middle:
    • Use two pointers (slow and fast) to find the middle of the linked list.
  2. Reverse the Second Half:
    • Reverse the second half of the linked list starting from the node after slow.
  3. Merge Two Halves:
    • Merge the first half and the reversed second half by alternating nodes.

Detailed Steps

Time Complexity

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next

class Solution:
    def reorderList(self, head: Optional[ListNode]) -> None:
        if not head or not head.next:
            return
        
        # find the middle
        slow, fast = head, head
        while fast and fast.next:
            slow = slow.next
            fast = fast.next.next
        
        # reverse the second half
        previous = None
        current = slow
        while current:
            next_node = current.next
            current.next = previous
            previous = current
            current = next_node
        
        # merge head with previous
        first, second = head, previous
        while second.next:
            temp1, temp2 = first.next, second.next
            first.next = second
            second.next = temp1
            first, second = temp1, temp2