Recursively Add Node to Linked List at Specific Index

JCCS

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.

Timo Hanisch

Regarding the valid index you could add a size field counting existing Nodes.

public class RecLinkedList {
    private int size = 0;

    //...
    private Node add( String s, Node list){
        if( list == null ){
            this.size += 1;
            return new Node(s);
        }else{
            list.setNext( add( s, list.getNext() ) );
            return list;
        }
    }
    //...
}

Then while adding a new Node with a method public void add(String value, int index) you could check if index is greater than the current size or less than zero.

To add the Node at the correct position just count the number of Nodes you've allready visited and when the correct position is reached add the Node.

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related