Skip to content

Commit 88d3c99

Browse files
committedDec 28, 2021
Add solution #24
1 parent b8027fe commit 88d3c99

File tree

2 files changed

+32
-0
lines changed

2 files changed

+32
-0
lines changed
 

‎README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,7 @@
2525
20|[Valid Parentheses](./0020-valid-parentheses.js)|Easy|
2626
21|[Merge Two Sorted Lists](./0021-merge-two-sorted-lists.js)|Easy|
2727
22|[Generate Parentheses](./0022-generate-parentheses.js)|Medium|
28+
24|[Swap Nodes in Pairs](./0024-swap-nodes-in-pairs.js)|Medium|
2829
27|[Remove Element](./0027-remove-element.js)|Easy|
2930
28|[Implement strStr()](./0028-implement-strstr.js)|Easy|
3031
31|[Next Permutation](./0031-next-permutation.js)|Medium|

‎solutions/0024-swap-nodes-in-pairs.js

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
/**
2+
* 24. Swap Nodes in Pairs
3+
* https://leetcode.com/problems/swap-nodes-in-pairs/
4+
* Difficulty: Medium
5+
*
6+
* Given a linked list, swap every two adjacent nodes and return its head. You must solve the
7+
* problem without modifying the values in the list's nodes (i.e., only nodes themselves may
8+
* be changed.)
9+
*/
10+
11+
/**
12+
* Definition for singly-linked list.
13+
* function ListNode(val, next) {
14+
* this.val = (val===undefined ? 0 : val)
15+
* this.next = (next===undefined ? null : next)
16+
* }
17+
*/
18+
/**
19+
* @param {ListNode} head
20+
* @return {ListNode}
21+
*/
22+
var swapPairs = function(head) {
23+
if (!head || !head.next) return head;
24+
25+
const result = head.next;
26+
head.next = result.next;
27+
result.next = head;
28+
head.next = swapPairs(head.next);
29+
30+
return result;
31+
};

0 commit comments

Comments
 (0)
Please sign in to comment.