LeetCode 1721. Swapping Nodes in a Linked List Solution in Java, C++, Python & More | Explanation + Code

CoderIndeed
0
1721. Swapping Nodes in a Linked List

Description

You are given the head of a linked list, and an integer k.

Return the head of the linked list after swapping the values of the kth node from the beginning and the kth node from the end (the list is 1-indexed).

 

Example 1:

Input: head = [1,2,3,4,5], k = 2
Output: [1,4,3,2,5]

Example 2:

Input: head = [7,9,6,6,7,8,3,0,9,5], k = 5
Output: [7,9,6,6,8,7,3,0,9,5]

 

Constraints:

  • The number of nodes in the list is n.
  • 1 <= k <= n <= 105
  • 0 <= Node.val <= 100

Solutions

Solution 1: Two Pointers

We can first use a fast pointer fast to find the kth node of the linked list, and use a pointer p to point to it. Then, we use a slow pointer slow to start from the head node of the linked list, and move both pointers forward at the same time. When the fast pointer reaches the last node of the linked list, the slow pointer slow points to the kth node from the end of the linked list, and we use a pointer q to point to it. At this point, we only need to swap the values of p and q.

The time complexity is O(n), where n is the length of the linked list. The space complexity is O(1).

PythonJavaC++GoTypeScriptC#
# 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]: fast = slow = head for _ in range(k - 1): fast = fast.next p = fast while fast.next: fast, slow = fast.next, slow.next q = slow p.val, q.val = q.val, p.val return head(code-box)

Post a Comment

0Comments

Post a Comment (0)

#buttons=(Accept !) #days=(20)

Our website uses cookies to enhance your experience. Check Now
Accept !