Skip to content

Commit 103c021

Browse files
authored
Merge pull request #2630 from TheHong/py-1721
Create 1721-swapping-nodes-in-a-linked-list.py
2 parents 39611ac + dd87ec1 commit 103c021

File tree

1 file changed

+20
-0
lines changed

1 file changed

+20
-0
lines changed
Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
# Definition for singly-linked list.
2+
# class ListNode:
3+
# def __init__(self, val=0, next=None):
4+
# self.val = val
5+
# self.next = next
6+
class Solution:
7+
def swapNodes(self, head: Optional[ListNode], k: int) -> Optional[ListNode]:
8+
right_pointer = head
9+
for _ in range(1, k):
10+
right_pointer = right_pointer.next
11+
left_kth_node = right_pointer
12+
13+
left_pointer = head
14+
while right_pointer is not None:
15+
right_kth_node = left_pointer
16+
right_pointer = right_pointer.next
17+
left_pointer = left_pointer.next
18+
19+
left_kth_node.val, right_kth_node.val = right_kth_node.val, left_kth_node.val
20+
return head

0 commit comments

Comments
 (0)