~/DHRUVUpskilling
← board/DSA/In place reversal LinkedList/dsa-in-place-reversal-linkedlist-05
Revision 2·26 Sept

Swapping Nodes in a Linked List

DifficultyMedium
PatternIn place reversal LinkedList
TrackDSA
tl;dr

Given the 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 of the linked list.

full write-up

Given the 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 of the linked list.

Statement

Given the 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 of the linked list.

Note: We'll number the nodes of the linked list starting from 1 to n.

Constraints

  • The linked list will have n number of nodes.
  • 1 ≤ k ≤ n ≤ 500
  • −5000 ≤ Node.value ≤ 5000

Examples

Example 1

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

Explanation: The 2nd node from the beginning has value 2, and the 2nd node from the end has value 4. Swapping their values gives [1, 4, 3, 2, 5].

Output: [1, 4, 3, 2, 5]

Example 2

Input: head = [7, 9, 6, 6, 8, 4] k = 3

Explanation: The 3rd node from the beginning has value 6, and the 3rd node from the end (position n - k + 1 = 4) has value 6. Since both values are the same, swapping them doesn't change the list.

Output: [7, 9, 6, 6, 8, 4]

Solution Use count and iterate curr to front k'th element. Then mark end to head and create a runner who's initial value would be front. when runner will reach to end of linked list end would be pointing to k from back. Now swap this both

function swapNodes(head, k) {
    // Step 1: move to the k-th node from the start (k-1 steps from head)
    let front = head;
    for (let i = 1; i < k; i++) {
        front = front.next;
    }

    // Step 2: use a runner starting at 'front' to find the k-th node from the end
    let end = head;
    let runner = front;
    while (runner.next !== null) {
        runner = runner.next;
        end = end.next;
    }

    // Step 3: swap values only
    [front.data, end.data] = [end.data, front.data];

    return head;
}


Swapping Nodes in a Linked List — pattern notes — Dhruv Parmar