LeetCode: Swapping Nodes In A Linked List Solution

1/**
2 * Definition for singly-linked list.
3 * function ListNode(val, next) {
4 * this.val = (val===undefined ? 0 : val)
5 * this.next = (next===undefined ? null : next)
6 * }
7 */
8/**
9 * @param {ListNode} head
10 * @param {number} k
11 * @return {ListNode}
12 */
13var swapNodes = function (head, k) {
14 let first = head
15 let second = head
16 let temp = head
17 let len = 0
18 while (temp) {
19 len++
20 temp = temp.next
21 }
22 let firstIndex = k - 1
23 let secondIndex = len - k
24 while (firstIndex--) {
25 first = first.next
26 }
27 while (secondIndex--) {
28 second = second.next
29 }
30 let tempVal = first.val
31 first.val = second.val
32 second.val = tempVal
33 return head
34}

Comments

Loading comments...

Tags

leetcode

linked list

Apply and earn a $2,500 bonus once you're hired on your first job!

Clients from the Fortune 500 to Silicon Valley startups

Choose your own rate, get paid on time

From hourly, part-time, to full-time positions

Flexible remote working environment

A lot of open JavaScript jobs!!

Fact corner: Referred talent are 5x more likely to pass the Toptal screening process than the average applicant.

Still hesitate? Read HoningJS author's guide on dealing with Toptal interview process.

Next Post

LeetCode: Integer To Roman

Mar 31, 2021

Previous Post

HoningJS

Search Posts