-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathReorderLinkedList.py
More file actions
62 lines (39 loc) · 1.01 KB
/
ReorderLinkedList.py
File metadata and controls
62 lines (39 loc) · 1.01 KB
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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
def printLinkedList(head):
current = head
while current:
print(current.val, end=" → ")
current = current.next
print("None")
def reorderList(head):
slow, fast = head, head
while fast and fast.next:
slow = slow.next
fast = fast.next.next
second_half = slow.next
slow.next = None
prev = None
current = second_half
while current:
temp = current.next
current.next = prev
prev = current
current = temp
first = head
second = prev
while second:
first_next = first.next
second_next = second.next
first.next = second
second.next = first_next
first = first_next
second = second_next
return head
head = ListNode(2)
head.next = ListNode(4)
head.next.next = ListNode(6)
head.next.next.next = ListNode(8)
printLinkedList(reorderList(head))