-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy path0024_swap_nodes_in_pairs.py
64 lines (48 loc) · 1.83 KB
/
0024_swap_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
# Link: https://leetcode.com/problems/swap-nodes-in-pairs/
######################
# ITERATIVE SOLUTION #
######################
class IterativeSolution:
def swapPairs(self, head: ListNode) -> ListNode:
# EDGE CASE: Linked list has zero or one node
if (head is None) or (head.next is None):
return head
left_node, right_node = head, head.next
# Store the second node as the new head
final_head = right_node
while left_node and right_node:
# Store reference to next left_node
next_left = right_node.next
if next_left:
next_right = right_node.next.next
else:
next_right = None
# Swap the left_node and right_node
right_node.next = left_node
left_node.next = next_right
# If there is an odd number of nodes
if (next_left) and (next_right is None):
left_node.next = next_left
break
# Move onto the next pair of nodes
left_node = next_left
right_node = next_right
return final_head
######################
# RECURSIVE SOLUTION #
######################
class RecursiveSolution:
def swapPairs(self, head: ListNode) -> ListNode:
# Base case: Undefined node or one node
if (head is None) or (head.next is None):
return head
left_node = head
right_node = head.next
# Figure out the value of left_node for the next recursive call
next_left = None
if (head.next):
next_left = right_node.next
# Swap the positions of the right node and left node
left_node.next = self.swapPairs(next_left)
right_node.next = left_node
return right_node