This is my attempted solution to exercise 2.4 in Cracking the Coding Interview.
The problem statement is:
Write code to partition a linked list around a value x such that all nodes less than x come before all nodes greater than or equal to x.
Example:
Input: \$ 3 \rightarrow 5 \rightarrow 8 \rightarrow 5 \rightarrow 10 \rightarrow 2 \rightarrow 1 \$
Output: \$ 3 \rightarrow 1 \rightarrow 2 \rightarrow 10 \rightarrow 5 \rightarrow 5 \rightarrow 8\$
I used the template code for a singly linked list from the book to write the Node
class and I wrote the method partition and a JUnit
test case for the method. I would appreciate any feedback on the algorithm for partition and the code overall.
Node.java
package practice_cracking_code_interview;
public class Node {
Node next = null;
int data;
public Node(int d){
data = d;
}
void appendToTail(int d){
Node end = new Node(d);
Node n = this;
while(n.next != null ){
n = n.next;
}
n.next = end;
}
Node partition(Node head, int x){
Node pRunner = head;
Node pHead = head;
Node pTemp = null;
while(pRunner != null && pRunner.next != null){
if(pRunner.next.data < x){
pTemp = pRunner.next.next;
pRunner.next.next = pHead;
pHead = pRunner.next;
pRunner.next = pTemp;
}
else{
pRunner = pRunner.next;
}
}
return pHead;
}
}
TestNode.java
package practice_cracking_code_interview;
import junit.framework.TestCase;
public class TestNode extends TestCase {
public void testAppendToTail(){
Node head = new Node(5);
head.appendToTail(10);
assertEquals(head.next.data, 10);
}
public void testPartitionOne(){
Node head = new Node(3);
head.appendToTail(5);
head.appendToTail(8);
head.appendToTail(5);
head.appendToTail(10);
head.appendToTail(2);
head.appendToTail(1);
Node n = head.partition(head, 5);
int[] expected = new int[]{1, 2, 3, 5, 8, 5, 10};
int i = 0;
while(n != null){
assertEquals(n.data, expected[i]);
i++;
n = n.next;
}
}
public void testPartitionTwo(){
Node head = new Node(3);
head.appendToTail(5);
head.appendToTail(8);
head.appendToTail(5);
head.appendToTail(10);
head.appendToTail(2);
head.appendToTail(1);
Node n = head.partition(head, 11);
int[] expected = new int[]{1, 2, 10, 5, 8, 5, 3};
int i = 0;
while(n != null){
assertEquals(n.data, expected[i]);
i++;
n = n.next;
}
}
}