Swapping Nodes in a Linked List Problem
#1721
Try it yourself first
Five languages, sample and hidden tests, right in the browser.
Practice it as an interview
Talk through your solution with an AI interviewer while you code.
Description
LeetCode Problem 1721.
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 k^th node from the beginning and the k^th 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 <= 10^50 <= Node.val <= 100
Solution
Approach: Two Pointers
Move a pointer fast forward k - 1 steps so that it sits on the kth node from the start; remember that node as p. Then start slow at the head and advance both pointers together until fast reaches the last node. At that moment slow is on the kth node from the end; call it q.
Swapping the values of p and q is enough, so there is no need to relink any nodes.
Complexity: O(n) time and O(1) space, where n is the length of the list.
# 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