【发布时间】:2018-11-24 01:36:59
【问题描述】:
我开始理解递归了,
我附上了合并两个排序链表的递归代码,
我的问题是,我知道一旦第一个或第二个变为空,'temp' 返回 temp->(first (or) second) 的值,但我无法理解这一事实,
例如,如果我有 5 -> 10 -> 15 -> 20。
最终函数返回 15 ->20,然后将其组合为 root.next-> temp,但是在我返回 temp 的那一步之后,为什么会返回根值。 即 10 -> 15 -> 20,当我希望只返回 temp 时。
请找到代码,
/**
*
*/
*
*
*/
public class MergeLinkedLists {
static class Node {
int data;
Node next;
public Node(int value) {
this.data = value;
}
}
Node root;
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
MergeLinkedLists s1 = new MergeLinkedLists();
s1.root = new Node(0);
Node n1 = new Node(10);
//n1.next = new Node(20);
//n1.next.next = new Node(30);
Node n2 = new Node(5);
n2.next = new Node(15);
//n2.next.next = new Node(50);
Node result = sortedLists(n1, n2, s1.root);
while (result != null) {
System.out.print(result.data + "--->");
result = result.next;
}
}
/**
* @param n1
* @param n2
* @param root2
*/
private static Node sortedLists(Node n1, Node n2, Node root) {
// TODO Auto-generated method stub
Node temp = root;
Node first = n1; // 10 20 30
Node second = n2; // 5 15 50
if (first == null) {
temp.next = second;
return temp;
} else if (second == null) {
temp.next = first;
return temp;
}
else if (first.data < second.data) {
temp = new Node(first.data);
first = first.next;
} else {
temp = new Node(second.data);
second = second.next;
}
sortedLists(first, second, temp);
root.next = temp;
System.out.println("The Temp Data is ::::"+temp.data);
return temp;
}
}
【问题讨论】:
-
欢迎来到 SO!这个函数的编写方式非常混乱,但据我所知,它工作得很好。你能澄清你的问题是什么吗?此处的返回值无关紧要,除了第一个函数调用,它将正确的结果(虚拟根的下一个值,即
root.next)返回到主范围。
标签: java recursion data-structures linked-list