我正在查看准备考试的示例,坦率地说,我不太擅长递归或列表,尤其是列表。
给定一个节点类,它将保存字符串(不是通用的),编写一个名为 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 {
}
}
感谢您的回复。
在这种情况下,递归是找到基本情况以及如何将数据“划分”到该基本情况。因此,首先定义您的“基本情况”。
- 基本情况:函数的参数为 null
- 直到获得基本情况,附加节点的文本并跳过第一个元素
这是你的方法:
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);
}
这个简单的例子将打印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));
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)