Reorder List
To solve this coding challenge, we need to reorder the given singly linked-list as per the specified pattern while ensuring that only the nodes themselves can be changed, not the values within them.
The reordering involves:
- Splitting the list into two halves.
- Reversing the second half.
- Merging the two halves in the prescribed order.
# Explanation
- Find the middle of the linked list: Use the slow and fast pointer technique. Slow pointer moves one step at a time while the fast pointer moves two steps. When the fast pointer reaches the end, the slow pointer will be at the middle.
- Reverse the second half of the linked list: Starting from the middle to the end, reverse the linked list to facilitate easy merging.
- Merge the two halves: Merge the first half and the reversed second half so that the nodes alternate from each half as per the requirement.
- Initialization & Edge Case Handling:
- If the list is empty or has only one node, no reordering is needed.
- Find the Middle:
-
Initialize two pointers,
slow
fast
-
Move
slow
fast
fast
Slow
- Reverse the Second Half:
-
Initialize two pointers,
prev
None
curr
slow
-
Traverse from the middle to the end of the list, reversing the pointers (i.e.,
curr.next = prev
- Merge the Two Halves:
-
Initialize two pointers,
first
head
second
prev
-
Alternate between advancing the
first
second
-
The
slow
3
fast
-
Reverse the list from the
slow
- Merge the two halves:
Detailed Steps in Pseudocode
# Pseudocode
# Function to reorder the list
function reorderList(head)
# Edge case: check if the list is empty or has a single node
if head is NULL or head.next is NULL
return
# Step 1: Find the middle of the linked list
slow = head
fast = head
while fast is not NULL and fast.next is not NULL
slow = slow.next
fast = fast.next.next
# Now, slow is at the middle node
# Step 2: Reverse the second half of the list
prev = NULL
curr = slow
while curr is not NULL
next_node = curr.next
curr.next = prev
prev = curr
curr = next_node
# Now, prev is the head of the reversed second half
# Step 3: Merge the two halves
first = head
second = prev
while second.next is not NULL
temp1 = first.next
first.next = second
first = temp1
temp2 = second.next
second.next = first
second = temp2
# List is now reordered according to the problem's requirements
end function
A visual rundown of these steps with an example list
[1, 2, 3, 4]
1 -> 2 -> 3 -> 4
^ ^
slow fast
1 -> 2 -> 3 <- 4
^ ^
slow prev
1 -> 4 -> 2 -> 3