Created
June 13, 2014 13:26
-
-
Save flexelem/504cf32a61bc8f24f46c to your computer and use it in GitHub Desktop.
Reverse a linked list by given K size slots with recursion
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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