【发布时间】:2010-01-31 11:14:58
【问题描述】:
给定两个排序链表 L1 和 L2,计算它们的解 路口L1路口L2。
【问题讨论】:
-
SO 的目的是灌输知识和理解,而不是给你模糊问题的完整解决方案。
标签: c algorithm data-structures
给定两个排序链表 L1 和 L2,计算它们的解 路口L1路口L2。
【问题讨论】:
标签: c algorithm data-structures
L1_node = L1.head;
L2_node = L2.head;
Result = new SList;
while L1_node != NULL and L2_node != NULL:
if L1_node.value == L2_node.value:
Result.append(L1_node.value)
L1_node = L1_node.next
L2_node = L2_node.next
elif L1_node.value < L2_node.value:
L1_node = L1_node.next
else
L2_node = L2_node.next
(自己翻译成C。)
【讨论】:
由于它们是单链表,如果两个链表相交,它们将形成一个 Y 形,其中一条臂长或等于另一条臂。令 l1 为 L1 列表的长度,l2 为 L2 列表的长度。
假设 l1 > l2。 从点 (l1-l2) 开始匹配 List L1 的指针,并从 L2 的开头开始匹配它们指向的相同节点,该节点将成为匹配点。
如果 l2 大于 l1 则执行其他方式。
【讨论】:
下面的解决方案怎么样,它是 O(n+m) 并且需要一个指向 Head 节点的虚拟节点。 Head 节点在这里是一个类级别的变量,所以即使 L1 指向当前,Head 总是有完整的列表。
我已经编译和测试,对于 L1: 1->5>6>7>8>10 和 L2:2>4>6>8 等简单输入运行良好,输出为 6>8
关于如何使用未排序列表的任何想法?我想不出一个 O(n) 的解决方案
public Node ReturnIntersection(Node Head, Node L2)
{
if ((Head == null) || (L2 == null))
return null;
Node temp = null;
Node L1 = Head;
while (L1.next != null && L2.next != null)
{
if (L1.data == L2.data)
{
L1 = L1.next;
L2 = L2.next;
}
else if (L1.data < L2.data)
{
temp = L1.next;
L1.data = temp.data;
L1.next = temp.next;
}
else if (L1.data > L2.data)
{
L2 = L2.next;
}
}
if (L1 != null)
{
while (L1.next != null)
{
L1.next = null;
}
}
return Head;
}
【讨论】: