Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to recursively concatenate a list of string elements

Tags:

java

I am looking at examples getting ready for an exam, and frankly, I am not very good with either recursion or lists, but particularly lists.

A node class is given, it will hold strings (not generic) write a recursive java function called concat that takes a node representing the head of a linked list and returns a string representing the concatenation of all the elements of the list if the list is empty the string should be as well.

Any help would be appreciated.

(The following is what I had type before I asked the question:)

public static String FindConcat(Node head) {
    String s = "";
    if(head == null) return s;
    else if(head.next = null) {
        s += head.data;
        return s;
    }
    else {

    }

}

Thanks for the repsonses.

like image 207
Blake Avatar asked Dec 06 '10 21:12

Blake


1 Answers

In this case what recursion is finding the base case and how to "devide" the data down to this base case. So first define your "base case".

  • Base case: argument to the function is null
  • Till you get the the base case, append the text of the node and skip the first element

This is your method:

public static String FindConcat(Node head) {
    if (head == null) 
        return ""; // base case

    // devide it down (run recursive FindConcat on the _next_ node)
    return head.data + FindConcat(head.next);
}

This simple example will print hello this is a linked list:

public class Test {
    // this is a very basic Node class
    static class Node {
        String text;
        Node next;

        public Node(String text) {
            this.text = text;
        }
        // used for building the list
        public Node add(String text) {
            next = new Node(text);
            return next;
        }
    }

    // this is the recursive method concat
    public static String concat(Node node) {
        if (node == null)
            return "";

        return node.text + " " + concat(node.next);
    }

    public static void main(String[] args) {
        // build the list
        Node head = new Node("hello");
        head.add("this").add("is").add("a").add("linked").add("list");

        // print the result of concat
        System.out.println(concat(head));
    }
}
like image 153
dacwe Avatar answered Oct 11 '22 23:10

dacwe