Problem
You are given the head of a singly linked-list. The list can be represented as:
L0 → L1 → … → Ln - 1 → Ln
Reorder the list to be on the following form:
L0 → Ln → L1 → Ln - 1 → L2 → Ln - 2 → …
You may not modify the values in the list’s nodes. Only nodes themselves may be changed.
Algorithm
Save the data in a list and then cover the data in the singly-linked list.
Code
# 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:
"""
Do not return anything, modify head in-place instead.
"""
save = []
p = head
while p:
save.append(p.val)
p = p.next
L, R = 0, len(save)-1
p = head
while L <= R:
if L <= R:
p.val = save[L]
L += 1
p = p.next
if L <= R:
p.val = save[R]
R -= 1
p = p.next