Skip to content

Commit 1690f1f

Browse files
author
Kai Yang
committed
25. Reverse Nodes in k-Group
1 parent 4e7426d commit 1690f1f

File tree

2 files changed

+86
-0
lines changed

2 files changed

+86
-0
lines changed

25.ReverseNodesInKGroup.Test.cs

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
using System;
2+
using Newtonsoft.Json;
3+
using NUnit.Framework;
4+
5+
[TestFixture]
6+
public class TestClass : TestClassBase
7+
{
8+
[TestCase(10, 10, 1000)]
9+
public void TestMethod(int maxLength, int maxValue, int repeatTimes)
10+
{
11+
Repeat(repeatTimes, () =>
12+
{
13+
var nums = GenerateIntegerArray(maxLength, maxValue);
14+
var original = JsonConvert.SerializeObject(nums);
15+
var head = ListNode.GetHead(nums);
16+
var k = nums.Length == 0 ? 0 : Random.Next(1, nums.Length + 1);
17+
ReverseKGroup(nums, k);
18+
var result = new Solution().ReverseKGroup(head, k);
19+
Assert.AreEqual(JsonConvert.SerializeObject(nums), ListNode.Serialize(result),
20+
string.Format("{0}. {1}.", original, k));
21+
});
22+
}
23+
24+
private void ReverseKGroup(int[] nums, int k)
25+
{
26+
if (k < 2) return;
27+
var i = 0;
28+
while (i + k <= nums.Length)
29+
{
30+
Array.Reverse(nums, i, k);
31+
i += k;
32+
}
33+
}
34+
}

25.ReverseNodesInKGroup.cs

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
public class Solution {
2+
public ListNode ReverseKGroup(ListNode head, int k) {
3+
if (k < 2) return head;
4+
ListNode newHead = null;
5+
ListNode newTail = null;
6+
var current = head;
7+
while (current != null)
8+
{
9+
ListNode segmentHead = null;
10+
ListNode segmentTail = null;
11+
var count = 0;
12+
while (current != null && count < k)
13+
{
14+
if (segmentHead == null) segmentHead = current;
15+
segmentTail = current;
16+
current = current.next;
17+
++count;
18+
}
19+
segmentTail.next = null;
20+
if (count == k)
21+
{
22+
segmentTail = segmentHead;
23+
segmentHead = ReverseList(segmentHead);
24+
}
25+
if (newHead == null)
26+
{
27+
newHead = segmentHead;
28+
newTail = segmentTail;
29+
}
30+
else
31+
{
32+
newTail.next = segmentHead;
33+
newTail = segmentTail;
34+
}
35+
}
36+
return newHead;
37+
}
38+
39+
private ListNode ReverseList(ListNode head)
40+
{
41+
var current = head;
42+
head = null;
43+
while (current != null)
44+
{
45+
var next = current.next;
46+
current.next = head;
47+
head = current;
48+
current = next;
49+
}
50+
return head;
51+
}
52+
}

0 commit comments

Comments
 (0)