Skip to content

Instantly share code, notes, and snippets.

@flexelem
Created June 13, 2014 13:26
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 flexelem/504cf32a61bc8f24f46c to your computer and use it in GitHub Desktop.
Save flexelem/504cf32a61bc8f24f46c to your computer and use it in GitHub Desktop.
Reverse a linked list by given K size slots with recursion
public class ReverseLinkedListKSizeSlots {
public Node reverseRecursion(Node root, int k) {
Node current = root;
Node prev = null;
Node next = null;
int count = 0;
while (current != null && count < k) {
next = current.next;
current.next = prev;
prev = current;
current = next;
count++;
}
if (next != null) {
root.next = reverseRecursion(next, k);
}
return prev;
}
}
import org.junit.Before;
import org.junit.Test;
public class ReverseLinkedListKSizeSlotsTest {
private ReverseLinkedListKSizeSlots testClass;
private LinkedList list;
@Before
public void setUp() {
testClass = new ReverseLinkedListKSizeSlots();
list = new LinkedList();
init();
}
@Test
public void test1() {
testClass.printKSizeSlotsReversed(list, 3);
}
@Test
public void tets2() {
Node head = testClass.reverseRecursion(list.head, 3);
Node temp = head;
while (temp != null) {
System.out.print(temp.data + " --> ");
temp = temp.next;
}
}
private void init() {
list = new LinkedList();
list.insert(1);
list.insert(2);
list.insert(3);
list.insert(4);
list.insert(5);
list.insert(6);
list.insert(7);
list.insert(8);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment