Losing head/tail while rewiring
Wrong move: Pointer updates overwrite references before they are saved.
Usually fails on: List becomes disconnected mid-operation.
Fix: Store next pointers first and use a dummy head for safer joins.
Move from brute-force thinking to an efficient approach using linked list strategy.
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:
n.1 <= k <= n <= 1050 <= Node.val <= 100Problem summary: 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).
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Pattern signal: Linked List · Two Pointers
[1,2,3,4,5] 2
[7,9,6,6,7,8,3,0,9,5] 5
remove-nth-node-from-end-of-list)swap-nodes-in-pairs)reverse-nodes-in-k-group)Source-backed implementations are provided below for direct study and interview prep.
// Accepted solution for LeetCode #1721: Swapping Nodes in a Linked List
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode swapNodes(ListNode head, int k) {
ListNode fast = head;
while (--k > 0) {
fast = fast.next;
}
ListNode p = fast;
ListNode slow = head;
while (fast.next != null) {
fast = fast.next;
slow = slow.next;
}
ListNode q = slow;
int t = p.val;
p.val = q.val;
q.val = t;
return head;
}
}
// Accepted solution for LeetCode #1721: Swapping Nodes in a Linked List
/**
* Definition for singly-linked list.
* type ListNode struct {
* Val int
* Next *ListNode
* }
*/
func swapNodes(head *ListNode, k int) *ListNode {
fast := head
for ; k > 1; k-- {
fast = fast.Next
}
p := fast
slow := head
for fast.Next != nil {
fast, slow = fast.Next, slow.Next
}
q := slow
p.Val, q.Val = q.Val, p.Val
return head
}
# Accepted solution for LeetCode #1721: Swapping Nodes in a Linked 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
// Accepted solution for LeetCode #1721: Swapping Nodes in a Linked List
struct Solution;
use rustgym_util::*;
impl Solution {
fn swap_nodes(head: ListLink, k: i32) -> ListLink {
let mut p = head;
let mut nodes: Vec<Box<ListNode>> = vec![];
let k = k as usize;
while let Some(mut node) = p {
p = node.next.take();
nodes.push(node);
}
let n = nodes.len();
nodes.swap(k - 1, n - k);
let mut prev = None;
while let Some(mut node) = nodes.pop() {
node.next = prev;
prev = Some(node);
}
prev
}
}
#[test]
fn test() {
let head = list!(1, 2, 3, 4, 5);
let k = 2;
let res = list!(1, 4, 3, 2, 5);
assert_eq!(Solution::swap_nodes(head, k), res);
let head = list!(7, 9, 6, 6, 7, 8, 3, 0, 9, 5);
let k = 5;
let res = list!(7, 9, 6, 6, 8, 7, 3, 0, 9, 5);
assert_eq!(Solution::swap_nodes(head, k), res);
let head = list!(1);
let k = 1;
let res = list!(1);
assert_eq!(Solution::swap_nodes(head, k), res);
let head = list!(1, 2);
let k = 1;
let res = list!(2, 1);
assert_eq!(Solution::swap_nodes(head, k), res);
let head = list!(1, 2, 3);
let k = 2;
let res = list!(1, 2, 3);
assert_eq!(Solution::swap_nodes(head, k), res);
}
// Accepted solution for LeetCode #1721: Swapping Nodes in a Linked List
/**
* Definition for singly-linked list.
* class ListNode {
* val: number
* next: ListNode | null
* constructor(val?: number, next?: ListNode | null) {
* this.val = (val===undefined ? 0 : val)
* this.next = (next===undefined ? null : next)
* }
* }
*/
function swapNodes(head: ListNode | null, k: number): ListNode | null {
let [fast, slow] = [head, head];
while (--k) {
fast = fast.next;
}
const p = fast;
while (fast.next) {
fast = fast.next;
slow = slow.next;
}
const q = slow;
[p.val, q.val] = [q.val, p.val];
return head;
}
Use this to step through a reusable interview workflow for this problem.
Copy all n nodes into an array (O(n) time and space), then use array indexing for random access. Operations like reversal or middle-finding become trivial with indices, but the O(n) extra space defeats the purpose of using a linked list.
Most linked list operations traverse the list once (O(n)) and re-wire pointers in-place (O(1) extra space). The brute force often copies nodes to an array to enable random access, costing O(n) space. In-place pointer manipulation eliminates that.
Review these before coding to avoid predictable interview regressions.
Wrong move: Pointer updates overwrite references before they are saved.
Usually fails on: List becomes disconnected mid-operation.
Fix: Store next pointers first and use a dummy head for safer joins.
Wrong move: Advancing both pointers shrinks the search space too aggressively and skips candidates.
Usually fails on: A valid pair can be skipped when only one side should move.
Fix: Move exactly one pointer per decision branch based on invariant.