I am writing a recursive function that will add an item to the list given an index by recursively iterating to the index and then adding the item. The function should take in 2 parameters (String value and integer index) and also check that the index is valid. Here is what I have so far which does not check for validity and only works when passing in just a String value.
Test Bench (Main)
public class TestBench {
public static void main(String[] args) {
RecLinkedList list = new RecLinkedList();
list.add("A");
list.add("B");
list.add("D");
list.add("C", 2);
list.add("E", 4);
list.add("G", 6); //this should be invalid
System.out.println( list );
System.out.println( list.remove( 1 ).getValue() );
System.out.println( list.remove("D").getValue() );
System.out.println( list.remove("G").getValue() );
System.out.println( list.size() );
System.out.println( list );
}
Linked List Class
public class RecLinkedList {
private Node first;
public RecLinkedList(){
first = null;
}
public boolean isEmpty() {
return first == null;
}
public void add( String s){
first = add( s, first);
}
private Node add( String s, Node list){
if( list == null ){
return new Node(s);
}else{
list.setNext( add( s, list.getNext() ) );
return list;
}
}
public String toString() {
return helperString(first);
}
private String helperString(Node list) {
if (list.getNext() != null) {
return list.getValue() + "," + helperString(list.getNext());
}
else {
return (String) list.getValue();
}
}
What I need help on is would I need to make another add function that takes in both parameters(String and int values) or if I can modify what I have? Also, as far as checking if the index is valid, I am not really sure how to check.