Skip to content

Instantly share code, notes, and snippets.

@InterviewBytes
Created June 8, 2017 02:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save InterviewBytes/6e1322d883bfc6539bc8a27d78f13fc3 to your computer and use it in GitHub Desktop.
Save InterviewBytes/6e1322d883bfc6539bc8a27d78f13fc3 to your computer and use it in GitHub Desktop.
Reverse Nodes in k-Group
package com.interviewbytes.linkedlists;
public class ListNode {
int val;
ListNode next;
ListNode(int x) {
val = x;
}
}
package com.interviewbytes.linkedlists;
public class ReverseKGroup {
public ListNode reverseKGroup(ListNode head, int k) {
if (head == null) return null;
int count = k;
ListNode current = head;
while (count > 0 && current != null) {
current = current.next;
count--;
}
if (count > 0) return head;
ListNode newHead = null;
current = head;
count = k;
while (count > 0 && current != null) {
ListNode next = current.next;
current.next = newHead;
newHead = current;
current = next;
count--;
}
if (current != null) head.next = reverseKGroup(current, k);
return newHead;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment