如何递归连接字符串元素列表

Bla*_*ake 5 java

我正在查看为考试做准备的示例,并且坦率地说,我对递归或列表(尤其是列表)都不满意。

给定一个节点类,它将保存字符串(不是通用的),编写一个名为concat的递归java函数,该函数接受一个表示链接列表头的节点,并返回一个字符串,该字符串表示列表中所有元素的串联。空字符串也应该如此。

任何帮助,将不胜感激。

(以下是我问问题之前输入的内容:)

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

    }

}
Run Code Online (Sandbox Code Playgroud)

感谢您的答复。

dac*_*cwe 5

在这种情况下,什么递归是找到基本情况以及如何将数据“分解”到这个基本情况。所以首先定义你的“基本情况”。

  • 基本情况:函数的参数为​​空
  • 直到获得基本情况,附加节点的文本并跳过第一个元素

这是你的方法:

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);
}
Run Code Online (Sandbox Code Playgroud)

这个简单的例子将打印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));
    }
}
Run Code Online (Sandbox Code Playgroud)


Kar*_*tel 0

如果您的节点为空,则返回空字符串。

否则,获取字符串,进行递归调用(以获取其余节点的串联结果),然后将其附加到字符串并返回结果。