-
Notifications
You must be signed in to change notification settings - Fork 0
/
#24 swapPairs.py
62 lines (49 loc) · 1.69 KB
/
#24 swapPairs.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
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
# def swapPairs(self, head: Optional[ListNode]) -> Optional[ListNode]:
# # Iterative solution
# # Here we want the header to be the item before anything
# # So that we can use the items at index 1 to be the new header
# header = ListNode(-1)
# header.next = head
# curr = header
# # If we don't have at least 2 more nodes for us to swap
# while curr.next is not None and curr.next.next is not None:
# odd = curr.next
# even = curr.next.next
# curr.next, odd.next, even.next = even, even.next, odd
# # Advance 2 units
# curr = curr.next.next
# return header.next
def swapPairs(self, head: Optional[ListNode]) -> Optional[ListNode]:
# Recursive solution
# If we are in the last 1 node or None, we don't swap
if head is None or head.next is None:
return head
header = head.next.next
head, head.next = head.next, head
head.next.next = self.swapPairs(header)
return head
# Another solution
# ans = ListNode()
# ans.next = head
# dummy = ans
#
# curr = head
#
# while curr is not None and curr.next is not None:
# two_steps = curr.next.next
#
# ans.next = curr.next
# ans = ans.next
# ans.next = curr
# ans = ans.next
# curr.next = two_steps
#
# curr = two_steps
#
# return dummy.next