Skip to content

Commit

Permalink
Merge pull request neetcode-gh#2630 from TheHong/py-1721
Browse files Browse the repository at this point in the history
Create 1721-swapping-nodes-in-a-linked-list.py
  • Loading branch information
MHamiid committed Jun 27, 2023
2 parents 39611ac + dd87ec1 commit 103c021
Showing 1 changed file with 20 additions and 0 deletions.
20 changes: 20 additions & 0 deletions python/1721-swapping-nodes-in-a-linked-list.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def swapNodes(self, head: Optional[ListNode], k: int) -> Optional[ListNode]:
right_pointer = head
for _ in range(1, k):
right_pointer = right_pointer.next
left_kth_node = right_pointer

left_pointer = head
while right_pointer is not None:
right_kth_node = left_pointer
right_pointer = right_pointer.next
left_pointer = left_pointer.next

left_kth_node.val, right_kth_node.val = right_kth_node.val, left_kth_node.val
return head

0 comments on commit 103c021

Please sign in to comment.