forked from ngiengkianyew/daily-coding-problem
-
Notifications
You must be signed in to change notification settings - Fork 0
/
problem_145.py
62 lines (45 loc) · 1.26 KB
/
problem_145.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
class Node:
def __init__(self, x):
self.val = x
self.next = None
def __str__(self):
string = "["
node = self
while node:
string += "{} ->".format(node.val)
node = node.next
string += "None]"
return string
def get_nodes(values):
next_node = None
for value in values[::-1]:
node = Node(value)
node.next = next_node
next_node = node
return next_node
def get_list(head):
node = head
nodes = list()
while node:
nodes.append(node.val)
node = node.next
return nodes
def swap_two_helper(node):
if not node or not node.next:
return node
first = node
second = node.next
tail = swap_two_helper(second.next)
second.next = first
first.next = tail
return second
def swap_two(head):
dummy_head = Node(0)
dummy_head.next = head
return swap_two_helper(head)
# Tests
assert get_list(swap_two(get_nodes([1]))) == [1]
assert get_list(swap_two(get_nodes([1, 2]))) == [2, 1]
assert get_list(swap_two(get_nodes([1, 2, 3, 4]))) == [2, 1, 4, 3]
assert get_list(swap_two(get_nodes([1, 2, 3, 4, 5]))) == [2, 1, 4, 3, 5]
assert get_list(swap_two(get_nodes([1, 2, 3, 4, 5, 6]))) == [2, 1, 4, 3, 6, 5]