伙计们,我试图按排序顺序合并两个排序的“单链列表”。在SO中,我找到了一种递归方法。我尽力理解代码,但无法完全理解!有谁可以帮助我清楚地找到答案。预先感谢!
以下是代码段:
Node MergeLists(Node list1, Node list2) {
if (list1 == null) return list2;
if (list2 == null) return list1;
if (list1.data < list2.data) {
list1.next = MergeLists(list1.next, list2);
return list1;
} else {
list2.next = MergeLists(list2.next, list1);
return list2;
}
}
链接:Interview: Merging two Sorted Singly Linked List
抱歉,浪费您的时间! :(
答案 0 :(得分:1)
这是我可以添加到代码中的内容:
Node MergeLists(Node list1, Node list2) {
if (list1 == null) return list2; //Exit strategy
if (list2 == null) return list1; //Exit strategy
if (list1.data < list2.data) { //If current item in list1 is less than current
//item in list2 we put the item of list1 in our
//sorted list and continue the algorithm recursivly
//and add the node from recursive function to list1.next
list1.next = MergeLists(list1.next, list2);
return list1;
} else { //exactly like above but this time we continue with list2
list2.next = MergeLists(list2.next, list1);
return list2;
}
}
答案 1 :(得分:1)
table2
最初,两个链接列表(LL1和LL2)中的每一个都将被排序(分别)。该代码仅合并它们。用 SIMPLE 示例
进行说明例如LL1;
SELECT a.word1, a.word2, b.word_name FROM table1 a, table2 b WHERE b.id = a.word1 OR b.id = a.word2
LL2:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Kin;
public class KinConnector : MonoBehaviour
{
private KinClient kinClient;
private KinAccount account;
void Start()
{
kinClient = new KinClient(Environment.Test, "test");
try
{
if (!kinClient.HasAccount())
{
account = kinClient.AddAccount();
//**NO ERROR RETURNED, JUST A NULL****
}
else
{
account = kinClient.GetAccount(0);
}
}
catch (KinException e)
{
Debug.LogError(e);
}
}
}
由于1. Node MergeLists(Node list1, Node list2) {
2. if (list1 == null) return list2;
3. if (list2 == null) return list1;
4. if (list1.data < list2.data) {
5. list1.next = MergeLists(list1.next, list2);
6. return list1;
7. } else {
8. list2.next = MergeLists(list2.next, list1);
9. return list2;
10. }
11. }
(第4行)将始终为真(直到基本退出条件(第2行)),因此LL1将递归直到结束。最后,(LL1的)最后一个元素的1->3->4
指向LL2的第一个元素(第5行)。这样,两个LL将被合并,我们将得到6->8->9
当然,在更复杂的示例中,会有更多的递归。