143 Reorder List
143 Reorder List
Reorder List 
You are given the head of a singly linked-list. The list can be represented as:
1
2
3
L0 → L1 → … → Ln - 1 → Ln
Reorder the list to be on the following form:
1
2
3
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.
Example 1:
1
2
3
4
**Input:** head = [1,2,3,4]
**Output:** [1,4,2,3]
Example 2:
1
2
3
4
**Input:** head = [1,2,3,4,5]
**Output:** [1,5,2,4,3]
Constraints:
1
2
The number of nodes in the list is in the range [1, 5 * 104].
1 <= Node.val <= 1000
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
temp = None
def reorderList(self, head: Optional[ListNode]) -> None:
"""
Do not return anything, modify head in-place instead.
"""
if head.next == None:
return
self.temp = head
result = head
self.Traverse( head, None)
head = result
def Traverse(self, head : ListNode, prev : ListNode) :
if head == None:
return
self.Traverse( head.next, head)
if head.next == None and prev != self.temp and self.temp != None and self.temp.next != None:
print(head, prev)
temp1 = self.temp.next
self.temp.next = head
head.next = temp1
self.temp = temp1
if prev != None:
prev.next = None
This post is licensed under CC BY 4.0 by the author.

