Skip to content

Commit 9d3c133

Browse files
Merge pull request kunal-kushwaha#476 from abhirajthakur/abhiraj
Modified reverseKGroup method so it does not reverse for less than k items
2 parents 45794cb + 7abd08e commit 9d3c133

File tree

1 file changed

+14
-7
lines changed

1 file changed

+14
-7
lines changed

lectures/18-linkedlist/code/src/com/kunal/InterviewQuestions.java

Lines changed: 14 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -180,21 +180,20 @@ public ListNode reverseBetween(ListNode head, int left, int right) {
180180

181181

182182
// google, amazon, facebook, microsoft: https://leetcode.com/problems/reverse-nodes-in-k-group/
183-
// its also reversing the < k end items -> modify it accordingly
184183
public ListNode reverseKGroup(ListNode head, int k) {
185184
if (k <= 1 || head == null) {
186185
return head;
187186
}
188187

189-
// skip the first left-1 nodes
190188
ListNode current = head;
191189
ListNode prev = null;
192190

193-
while (true) {
191+
int length = getLength(head);
192+
int count = length / k;
193+
while (count > 0) {
194194
ListNode last = prev;
195195
ListNode newEnd = current;
196196

197-
// reverse between left and right
198197
ListNode next = current.next;
199198
for (int i = 0; current != null && i < k; i++) {
200199
current.next = prev;
@@ -213,14 +212,22 @@ public ListNode reverseKGroup(ListNode head, int k) {
213212

214213
newEnd.next = current;
215214

216-
if (current == null) {
217-
break;
218-
}
219215
prev = newEnd;
216+
count--;
220217
}
221218
return head;
222219
}
223220

221+
public int getLength(ListNode head) {
222+
ListNode node = head;
223+
int length = 0;
224+
while (node != null) {
225+
length++;
226+
node = node.next;
227+
}
228+
return length;
229+
}
230+
224231
// https://www.geeksforgeeks.org/reverse-alternate-k-nodes-in-a-singly-linked-list/
225232
public ListNode reverseAlternateKGroup(ListNode head, int k) {
226233
if (k <= 1 || head == null) {

0 commit comments

Comments
 (0)