Skip to content

Instantly share code, notes, and snippets.

@nashid
Last active November 8, 2016 22:01
Show Gist options
  • Save nashid/99e9ea7f8036e3e2fe347c08a7c262fe to your computer and use it in GitHub Desktop.
Save nashid/99e9ea7f8036e3e2fe347c08a7c262fe to your computer and use it in GitHub Desktop.
Reverse every k nodes in linked list
package kata.linkedlist;
public class ReverseKNodeLinkedList {
public static Node reverseKNodes(Node node, int k) {
if (node == null || node.getNext() == null) {
return node;
}
int n = 0;
Node head_prev = node, head_next = null, curr = node, prev = null, tail = node;
while (curr != null && n < k) {
if (curr.getNext() == null || n == k - 1) {
head_prev = curr;
}
Node next = curr.getNext();
curr.setNext(prev);
prev = curr;
curr = next;
n++;
}
head_next = reverseKNodes(curr, k);
if (head_next != null) {
tail.setNext(head_next);
}
return head_prev;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment