Swapping Nodes in a Linked List

Swap values (not nodes) of the kth-from-start and kth-from-end positions with a single offset-pointer pass.

Medium
Time O(n) Space O(1)
LeetCode
3 min read
linked-list two-pointers

Problem#

Swap the values of the kth node from the beginning and the kth from the end of a singly linked list. Return the head.

Examples#

  • [1,2,3,4,5], k = 2[1,4,3,2,5]

Constraints#

  • 1 <= k <= length.

Approach#

Single pass. Walk kth to the kth node (front pointer). Then walk a second pointer from head while kth finishes its traversal — the gap of length - k lands the second pointer on the kth-from-end node. Swap values.

Solution#

Swapping Nodes in a Linked List
class Solution {
public:
ListNode* swapNodes(ListNode* head, int k) {
ListNode *p = head;
for (int i = 1; i < k; ++i) p = p->next;
ListNode *first = p, *second = head;
while (p->next) { p = p->next; second = second->next; }
swap(first->val, second->val);
return head;
}
};

Editorial#

Same gap-of-k technique used for “nth from end”. After we anchor first at the kth node and walk a second pointer in lockstep with the rest of the traversal, the second pointer is automatically at length - k, which 1-indexed is the kth from end. Swapping values avoids any pointer surgery.

Complexity#

  • Time: O(n).
  • Space: O(1).

Concept revision#

Search ESC

Keyboard shortcuts

Shortcuts are disabled while typing in inputs.