-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSwap_Nodes_In_Pairs.py
More file actions
53 lines (33 loc) · 1.08 KB
/
Swap_Nodes_In_Pairs.py
File metadata and controls
53 lines (33 loc) · 1.08 KB
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
Given a linked list, swap every two adjacent nodes and return its head.
You may not modify the values in the list-s nodes. Only nodes itself 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
# My Solution
class Solution:
def swapPairs(self, head: ListNode) -> ListNode:
dummy = ListNode()
dummy.next = head
current = dummy
while current.next and current.next.next:
node_1 = current.next
node_2 = current.next.next
node_1.next = node_2.next
current.next = node_2
current.next.next = node_1
current = current.next.next
return dummy.next