Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
Skip to content

Commit 5496b17

Browse files
committed
Add solution #1721
1 parent ddbe855 commit 5496b17

File tree

2 files changed

+44
-1
lines changed

2 files changed

+44
-1
lines changed

README.md

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
# 1,499 LeetCode solutions in JavaScript
1+
# 1,500 LeetCode solutions in JavaScript
22

33
[https://leetcodejavascript.com](https://leetcodejavascript.com)
44

@@ -1326,6 +1326,7 @@
13261326
1718|[Construct the Lexicographically Largest Valid Sequence](./solutions/1718-construct-the-lexicographically-largest-valid-sequence.js)|Medium|
13271327
1719|[Number Of Ways To Reconstruct A Tree](./solutions/1719-number-of-ways-to-reconstruct-a-tree.js)|Hard|
13281328
1720|[Decode XORed Array](./solutions/1720-decode-xored-array.js)|Easy|
1329+
1721|[Swapping Nodes in a Linked List](./solutions/1721-swapping-nodes-in-a-linked-list.js)|Medium|
13291330
1726|[Tuple with Same Product](./solutions/1726-tuple-with-same-product.js)|Medium|
13301331
1732|[Find the Highest Altitude](./solutions/1732-find-the-highest-altitude.js)|Easy|
13311332
1748|[Sum of Unique Elements](./solutions/1748-sum-of-unique-elements.js)|Easy|
Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
/**
2+
* 1721. Swapping Nodes in a Linked List
3+
* https://leetcode.com/problems/swapping-nodes-in-a-linked-list/
4+
* Difficulty: Medium
5+
*
6+
* You are given the head of a linked list, and an integer k.
7+
*
8+
* Return the head of the linked list after swapping the values of the kth node from the beginning
9+
* and the kth node from the end (the list is 1-indexed).
10+
*/
11+
12+
/**
13+
* Definition for singly-linked list.
14+
* function ListNode(val, next) {
15+
* this.val = (val===undefined ? 0 : val)
16+
* this.next = (next===undefined ? null : next)
17+
* }
18+
*/
19+
/**
20+
* @param {ListNode} head
21+
* @param {number} k
22+
* @return {ListNode}
23+
*/
24+
var swapNodes = function(head, k) {
25+
let firstNode = head;
26+
for (let i = 1; i < k; i++) {
27+
firstNode = firstNode.next;
28+
}
29+
30+
let slow = head;
31+
let secondNode = firstNode.next;
32+
while (secondNode) {
33+
slow = slow.next;
34+
secondNode = secondNode.next;
35+
}
36+
37+
const temp = firstNode.val;
38+
firstNode.val = slow.val;
39+
slow.val = temp;
40+
41+
return head;
42+
};

0 commit comments

Comments
 (0)