-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathswap_list_nodes_in_pairs.py
115 lines (84 loc) · 2.35 KB
/
swap_list_nodes_in_pairs.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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
class ListNode:
def __init__(self, val):
self.val = val
self.next = None
def __repr__(self):
return 'Node<{},{}>'.format(self.val, self.next)
def swap_nodes_in_pairs(head):
# Keep new head around to return it at last
if head.next:
new_head = head.next
else:
return head
while head is not None:
first_node = head
second_node = first_node.next
third_node = second_node.next if second_node else None
forth_node = third_node.next if third_node else None
if second_node:
second_node.next = first_node
if forth_node:
first_node.next = forth_node
else:
first_node.next = third_node
head = third_node
return new_head
def test_one_node_swap():
a1 = ListNode(1)
assert swap_nodes_in_pairs(a1) == a1
def test_swap():
a1 = ListNode(1)
a2 = ListNode(2)
a3 = ListNode(3)
a4 = ListNode(4)
a5 = ListNode(5)
a6 = ListNode(6)
a1.next = a2
a2.next = a3
a3.next = a4
a4.next = a5
a5.next = a6
swapped_head = swap_nodes_in_pairs(a1)
assert swapped_head == a2
swapped_head = swapped_head.next
assert swapped_head == a1
swapped_head = swapped_head.next
assert swapped_head == a4
swapped_head = swapped_head.next
assert swapped_head == a3
swapped_head = swapped_head.next
assert swapped_head == a6
swapped_head = swapped_head.next
assert swapped_head == a5
def test_uneven_swap():
a1 = ListNode(1)
a2 = ListNode(2)
a3 = ListNode(3)
a4 = ListNode(4)
a5 = ListNode(5)
a1.next = a2
a2.next = a3
a3.next = a4
a4.next = a5
swapped_head = swap_nodes_in_pairs(a1)
assert swapped_head == a2
swapped_head = swapped_head.next
assert swapped_head == a1
swapped_head = swapped_head.next
assert swapped_head == a4
swapped_head = swapped_head.next
assert swapped_head == a3
swapped_head = swapped_head.next
assert swapped_head == a5
def test_uneven_small_swap():
a1 = ListNode(1)
a2 = ListNode(2)
a3 = ListNode(3)
a1.next = a2
a2.next = a3
swapped_head = swap_nodes_in_pairs(a1)
assert swapped_head == a2
swapped_head = swapped_head.next
assert swapped_head == a1
swapped_head = swapped_head.next
assert swapped_head == a3