-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlinklist.py
57 lines (45 loc) · 1.3 KB
/
linklist.py
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
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
def reorderList(head: ListNode) -> None:
if not head or not head.next or not head.next.next:
return
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
while second_half:
next_node = second_half.next
second_half.next = prev
prev = second_half
second_half = next_node
first_half = head
second_half = prev
while second_half:
temp1, temp2 = first_half.next, second_half.next
first_half.next = second_half
second_half.next = temp1
first_half = temp1
second_half = temp2
def print_list(head: ListNode) -> None:
while head:
print(head.val, end=" -> " if head.next else "")
head = head.next
print()
def create_linked_list(arr):
dummy = ListNode()
current = dummy
for val in arr:
current.next = ListNode(val)
current = current.next
return dummy.next
head = create_linked_list([1, 2, 3, 4, 5, 6])
print("Original List:")
print_list(head)
reorderList(head)
print("Reordered List:")
print_list(head)