-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path24.py
44 lines (33 loc) · 1.01 KB
/
24.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
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
# Swap the value not the node
class Solution:
def swapPairs(self, head: ListNode) -> ListNode:
node = head
while node and node.next:
node.val, node.next.val = node.next.val, node.val
node = node.next.next
return head
# Recursive
class Solution2:
def swapPairs(self, head: ListNode) -> ListNode:
if not head or not head.next:
return head
first_node = head
second_node = head.next
first_node.next = self.swapPairs(second_node.next)
second_node.next = first_node
return second_node
# Iterative
class Solution3:
def swapPairs(self, head):
pre, pre.next = self, head
while pre.next and pre.next.next:
a = pre.next
b = a.next
pre.next, b.next, a.next = b, a, b.next
pre = a
return self.next