简体   繁体   中英

Replacing strings recursively in a Linked list in Java

Trying to create a method that will replace all instances of a string in a linked list with the chosen replacement string.

However, what I've got only seems to check the node chosen by the third argument, and does not recur through the list.

public void replace(String firstItem, String replaceItem, Node n){
    if (n != null) {
        if (n.getItem().equals(firstItem)) {
            n.setItem(replaceItem);
            n = n.next();
        }
    }
}

Here is the main app:

public class ListApp {

    public static void main(String[] args){
        Node n4 = new Node("green", null);
        Node n3 = new Node("red", n4);
        Node n2 = new Node("red", n3);
        Node n1 = new Node("red", n2);

        LinkedList list = new LinkedList(n1);

        System.out.println(list);

        list.replace("red", "RED", n1); // CALLING THE METHOD

        System.out.println(list);

    }
}

However the output comes out as:

RED, red, red, green

Not sure what I need to do to make it so it checks every node.

If needed, the node library:

package lib;

public class Node {
    private String item;
    private Node nextItem;

    public Node(String str, Node n){
        item = str;
        nextItem = n;
    }
    public String getItem(){
        return item;
    }
    public void setItem(String str){
        item = str;
    }
    public Node next(){
        return nextItem;
    }
    public void setNext(Node n){
        nextItem = n;
    }
}

Any information would be greatly appreciated, thanks!

The problem with your code is, that you do not call the function recursivly.

Furthermore, you might want to get the next node every time, not only when you replaced an item.

Therefore, you code should look like this:

public void replace(String firstItem, String replaceItem, Node n){
    if (n != null) {
        if (n.getItem().equals(firstItem)) {
            n.setItem(replaceItem);
        }
        replace (firstItem, replaceItem, n.next());
    }
}

You almost had it:

public void replace(String firstItem, String replaceItem, Node n){
    if (n != null) {
        if (n.getItem().equals(firstItem)) {
            n.setItem(replaceItem);
            n = n.next();
        }
        replace(firstItem, replaceItem, n); //Recursive call here
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM