Assuming:
The task is to reorder a list such that:
Given L0 → L1 → … → Ln-1 → Ln
, reorder it to L0 → Ln → L1 → Ln-1 → L2 → Ln-2 → …
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
def reorderList(head):
if not head or not head.next:
return
# Step 1: Find the middle of the linked list
slow, fast = head, head
while fast and fast.next:
slow = slow.next
fast = fast.next.next
# Step 2: Reverse the second half of the list
prev, curr = None, slow.next
slow.next = None # Cut the list into two halves
while curr:
next_temp = curr.next
curr.next = prev
prev = curr
curr = next_temp
# Step 3: Merge the two halves
first, second = head, prev
while second:
next_first, next_second = first.next, second.next
first.next = second
second.next = next_first
first, second = next_first, next_second
# Example usage
# Let's create a list: 1->2->3->4
head = ListNode(1)
head.next = ListNode(2)
head.next.next = ListNode(3)
head.next.next.next = ListNode(4)
reorderList(head)
# The list should be reordered to 1->4->2->3
Overall, the time complexity is O(n) where n
is the number of nodes in the list.
Feel free to ask any further clarifying questions or simulating additional test cases to ensure the solution is robust!
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?