Skip to content

1721. Swapping Nodes in a Linked List 👍

  • Time: $O(n)$
  • Space: $O(1)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
class Solution {
 public:
  ListNode* swapNodes(ListNode* head, int k) {
    ListNode* p = nullptr;  // Points the k-th node from the beginning.
    ListNode* q = nullptr;  // Points the k-th node from the end.

    for (ListNode* curr = head; curr != nullptr; curr = curr->next) {
      if (q != nullptr)
        q = q->next;
      if (--k == 0) {
        p = curr;
        q = head;
      }
    }

    swap(p->val, q->val);
    return head;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
class Solution {
  public ListNode swapNodes(ListNode head, int k) {
    ListNode p = null; // Points the k-th node from the beginning.
    ListNode q = null; // Points the k-th node from the end.

    for (ListNode curr = head; curr != null; curr = curr.next) {
      if (q != null)
        q = q.next;
      if (--k == 0) {
        p = curr;
        q = head;
      }
    }

    final int temp = p.val;
    p.val = q.val;
    q.val = temp;
    return head;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
class Solution:
  def swapNodes(self, head: ListNode | None, k: int) -> ListNode | None:
    p = None  # Points the k-th node from the beginning.
    q = None  # Points the k-th node from the end.

    curr = head
    while curr:
      if q:
        q = q.next
      k -= 1
      if k == 0:
        p = curr
        q = head
      curr = curr.next

    p.val, q.val = q.val, p.val
    return head