DEV Community

codingpineapple
codingpineapple

Posted on

1721. Swapping Nodes in a Linked List (javascript solution)

Description:

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).

Solution:

Time Complexity : O(n)
Space Complexity: O(1)

// We only need to switch the vals in the problem not the nodes.
// Create a dummy node at the front of the linked list.
// Move a pointer from the dummy up to the kth node and save the kth node to a variable called front.
// Create a new pointer at the dummy node call back.
// Continue moving the original pointer and the back pointer until the original pointer is null.
// Switch the values of back and front
var swapNodes = function(head, k) {
    let dummy = new ListNode(0, head);
    let front = dummy;
    let back = dummy;    
    let pointer = dummy;

    for(let i = k; i > 0; i--) {
        pointer = pointer.next
    }
    front = pointer
    while(pointer) {
        pointer = pointer.next
        back = back.next
    }

    const temp = front.val
    front.val = back.val
    back.val = temp

    return head;
};
Enter fullscreen mode Exit fullscreen mode

Top comments (0)