Categories

## 1721. Swapping Nodes in a Linked List Leetcode Javascript Solution

The Problem:

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]
```

Example 3:

```Input: head = [1], k = 1
Output: [1]
```

Example 4:

```Input: head = [1,2], k = 1
Output: [2,1]
```

Example 5:

```Input: head = [1,2,3], k = 2
Output: [1,2,3]
```

Constraints:

• The number of nodes in the list is `n`.
• `1 <= k <= n <= 105`
• `0 <= Node.val <= 100`

The Solution:

I got stuck at trying a new element swapping method with ES6 and wasted a good amount of time. In the end, I printed out variables line by line and used the old swapping method.

```var swapNodes = function(head, k) {
let dummy = new ListNode(0)
let fast = dummy, slow = dummy
for(let i = 1; i <= k; i++){
fast = fast.next
}
//  console.log(fast.val)
let first = fast
while(fast.next != null){
slow = slow.next
fast = fast.next
}
let second = slow.next
//console.log("first: " + first.val + " second: " + second.val)
// first.val, second.val = second.val, first.val
//let a = 2, b = 4
let temp = first.val
first.val = second.val
second.val = temp
// console.log( "a: " + a + " b: " + b)
// console.log("first: " + first.val + " second: " + second.val)
return dummy.next
};```