-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSolution25.cs
61 lines (51 loc) · 1.6 KB
/
Solution25.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
using LeetCode.DataStructures;
namespace LeetCode.Solutions;
public class Solution25
{
/// <summary>
/// 25. Reverse Nodes in k-Group
/// <a href="https://leetcode.com/problems/reverse-nodes-in-k-group">See the problem</a>
/// </summary>
public ListNode ReverseKGroup(ListNode head, int k)
{
if (head == null || k == 1) {
return head;
}
// Dummy node
var dummy = new ListNode(0) {
next = head
};
// Count the number of nodes in the list
var current = head;
var count = 0;
while (current != null) {
count++;
current = current.next;
}
// Reverse in groups
var prevTail = dummy;
var nextHead = dummy.next;
while (count >= k) {
current = nextHead;
ListNode prev = null;
// Reverse k nodes
for (var i = 0; i < k; i++) {
var next = current.next;
current.next = prev;
prev = current;
current = next;
}
// Connect the reversed group with the rest of the list
// prevTail.next points to the start of the reversed group
// prevTail is updated to the start of the group before reversal
var temp = prevTail.next;
prevTail.next = prev;
prevTail = temp;
prevTail.next = current;
// Update nextHead for the next group
nextHead = current;
count -= k;
}
return dummy.next;
}
}