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} head10 * @param {number} k11 * @return {ListNode}12 */13var swapNodes = function (head, k) {14 let first = head15 let second = head16 let temp = head17 let len = 018 while (temp) {19 len++20 temp = temp.next21 }22 let firstIndex = k - 123 let secondIndex = len - k24 while (firstIndex--) {25 first = first.next26 }27 while (secondIndex--) {28 second = second.next29 }30 let tempVal = first.val31 first.val = second.val32 second.val = tempVal33 return head34}
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
LeetCode: Russian Doll Envelopes
Mar 31, 2021