【发布时间】:2014-01-15 04:52:29
【问题描述】:
我想编写一个代码来合并两个链表,以使结果列表没有重复。这两个列表是有序的,但其中可能有重复。结果列表应存储在当前列表中。代码应该在O(n1+n2) 时间运行,其中 n1 是当前列表的大小,n2 是另一个列表的大小。
这是一个合并两个列表但重复的代码。这段代码的运行时间是O(n1+n2),它将结果列表存储到当前列表中:
template <class T>
void DLList<T>::MergeInOrder(DLList<T>& otherList)
{
if(otherList.IsEmpty() == true)
return;
if(IsEmpty() == true)
{
Append(otherList);
return;
}
DLList<T> newList;
DLLNode<T> *thisPtr, *otherPtr;
for(thisPtr = this->head, otherPtr = otherList.head;
thisPtr != NULL || otherPtr != NULL; )
{
if(otherPtr == NULL)
{
newList.AddToTail(thisPtr->val);
thisPtr = thisPtr->next;
}
else if(thisPtr == NULL)
{
newList.AddToTail(otherPtr->val);
otherPtr = otherPtr->next;
}
else if(thisPtr->val <= otherPtr->val)
{
newList.AddToTail(thisPtr->val);
thisPtr = thisPtr->next;
}
else
{
newList.AddToTail(otherPtr->val);
otherPtr = otherPtr->next;
}
}
Clear();
Append(newList);
}
有什么遗漏的信息吗?
【问题讨论】:
-
为什么不使用 set_union? cplusplus.com/reference/algorithm/set_union
-
这是归并排序的归并算法。然而,它依赖于列表不包含重复项的假设,因此它在这里不起作用。考虑两个列表:
1 1和2 2。此代码将连续添加两个1s,因为它们都小于2。 -
您对列表中的元素,特别是它们的顺序有任何保证吗?也就是说,如果 x 在 L1 中出现在 y 之后,那么 x' 在 L2 中出现在 y' 之后?
-
这两个列表必须按降序排列。上面的代码可以正常工作,但不考虑重复。