Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit d60a3c9

Browse files
reverse-nodes-in-k-group
1 parent 83507f2 commit d60a3c9

File tree

2 files changed

+95
-0
lines changed

2 files changed

+95
-0
lines changed
Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
# Merge k Sorted Lists
2+
3+
Given a linked list, reverse the nodes of a linked list k at a time and return its modified list.
4+
5+
k is a positive integer and is less than or equal to the length of the linked list. If the number of nodes is not a multiple of k then left-out nodes in the end should remain as it is.
6+
7+
## Example
8+
9+
Given this linked list: 1->2->3->4->5
10+
11+
For k = 2, you should return: 2->1->4->3->5
12+
13+
For k = 3, you should return: 3->2->1->4->5
14+
15+
## Note
16+
17+
Only constant extra memory is allowed.
18+
19+
You may not alter the values in the list's nodes, only nodes itself may be changed.
20+
21+
## More Info
22+
23+
<https://leetcode.com/problems/reverse-nodes-in-k-group/>
Lines changed: 72 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,72 @@
1+
/**
2+
* Definition for singly-linked list.
3+
* function ListNode(val) {
4+
* this.val = val;
5+
* this.next = null;
6+
* }
7+
*/
8+
9+
function ListNode(val) {
10+
this.val = val;
11+
this.next = null;
12+
}
13+
14+
/**
15+
* @param {ListNode} head
16+
* @param {number} k
17+
* @return {ListNode}
18+
*/
19+
var reverseKGroup = function(head, k) {
20+
let temp = new ListNode(null);
21+
temp.next = head;
22+
let start = temp;
23+
24+
while(true){
25+
let counter = 0;
26+
let tempK = temp;
27+
while(tempK && counter++<k){
28+
tempK = tempK.next;
29+
}
30+
31+
if (!tempK && counter !== k + 1) break;
32+
33+
counter=0;
34+
let a = temp.next;
35+
while (++counter < k) {
36+
let b = a.next;
37+
a.next = b.next;
38+
b.next = temp.next;
39+
temp.next = b;
40+
}
41+
temp = a;
42+
}
43+
return start.next;
44+
};
45+
46+
function print(n) {
47+
var t = n;
48+
var s = '';
49+
while (t) {
50+
s = s + t.val + '->';
51+
t = t.next;
52+
}
53+
s += 'null';
54+
return s;
55+
}
56+
57+
console.log(print(reverseKGroup({
58+
val: 1,
59+
next: {
60+
val: 2,
61+
next: {
62+
val: 3,
63+
next: {
64+
val: 4,
65+
next: {
66+
val: 5
67+
}
68+
}
69+
}
70+
}
71+
}, 3)));
72+

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /