Rearrange a Linked List from Alternating Ends
Problem statement
Rearrange a singly linked list L0 → L1 → … → Ln into L0 → Ln → L1 → Ln-1 → ….
Reuse the existing nodes and return the head. Do not change node values.
Function
rearrangeList(head: ListNode) → ListNodeExamples
Example 1
head = [1,2,3,4]return = [1,4,2,3]The alternating order is 1,4,2,3.
Example 2
head = [1,2,3,4,5]return = [1,5,2,4,3]The middle node remains last.
Example 3
head = []return = []An empty list stays empty.
Constraints
- The list contains at most
100000nodes. - Node values fit in a signed 32-bit integer.