Skip to content

Commit 1ffa7d8

Browse files
Add files via upload
1 parent 8fb894b commit 1ffa7d8

File tree

1 file changed

+57
-0
lines changed

1 file changed

+57
-0
lines changed

linklist.py

+57
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
class ListNode:
2+
def __init__(self, val=0, next=None):
3+
self.val = val
4+
self.next = next
5+
6+
def reorderList(head: ListNode) -> None:
7+
if not head or not head.next or not head.next.next:
8+
return
9+
slow, fast = head, head
10+
while fast and fast.next:
11+
slow = slow.next
12+
fast = fast.next.next
13+
second_half = slow.next
14+
slow.next = None
15+
prev = None
16+
while second_half:
17+
next_node = second_half.next
18+
second_half.next = prev
19+
prev = second_half
20+
second_half = next_node
21+
first_half = head
22+
second_half = prev
23+
24+
while second_half:
25+
26+
temp1, temp2 = first_half.next, second_half.next
27+
28+
29+
first_half.next = second_half
30+
second_half.next = temp1
31+
32+
33+
first_half = temp1
34+
second_half = temp2
35+
36+
def print_list(head: ListNode) -> None:
37+
while head:
38+
print(head.val, end=" -> " if head.next else "")
39+
head = head.next
40+
print()
41+
42+
def create_linked_list(arr):
43+
dummy = ListNode()
44+
current = dummy
45+
for val in arr:
46+
current.next = ListNode(val)
47+
current = current.next
48+
return dummy.next
49+
50+
head = create_linked_list([1, 2, 3, 4, 5, 6])
51+
print("Original List:")
52+
print_list(head)
53+
54+
reorderList(head)
55+
56+
print("Reordered List:")
57+
print_list(head)

0 commit comments

Comments
 (0)