-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path24_Swap_Nodes_in_Pairs.py
50 lines (39 loc) · 1.29 KB
/
24_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
"""
Given a linked list, swap every two adjacent nodes and return its head. You must solve the problem without modifying the values in the list's nodes (i.e., only nodes themselves may be changed.)
Example 1:
Input: head = [1,2,3,4]
Output: [2,1,4,3]
Example 2:
Input: head = []
Output: []
Example 3:
Input: head = [1]
Output: [1]
Constraints:
- The number of nodes in the list is in the range [0, 100].
- 0 <= Node.val <= 100
"""
# 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]:
# fake node to save the starting point
fake_node = ListNode(next=head)
# instantiate
prev_node = fake_node
current_node = head
while current_node and current_node.next:
# save the pointers
next_node = current_node.next
nextpair = current_node.next.next
# swap pointers
next_node.next = current_node
current_node.next = nextpair
prev_node.next = next_node
# increment
prev_node = current_node
current_node = nextpair
return fake_node.next