# LeetCode: Swapping Nodes In A Linked List Solution

`.css-ds3kc{display:table-row;}.css-1t8atru{display:table-cell;opacity:0.5;padding-right:var(--chakra-space-6);-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none;text-align:right;}1.css-2qghsv{display:table-cell;}/**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}`

leetcode

## Next Post

LeetCode: Integer To Roman

Mar 31, 2021

Search Posts