[英]Merging two linked lists with no duplication
我想編寫一個代碼來合並兩個鏈接列表,以使結果列表沒有重復 。 這兩個列表是有序的,但其中可能有重復項。 結果列表應存儲在當前列表中。 該代碼應在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);
}
缺少任何信息嗎?
用以下調用替換迭代器的每個增量 :
DLLNode<T>* nextDifferent(DLLNode<T> &node)
{
const T& val = node.val;
DLLNode<T> *res = node.next;
while (res != nullptr && res->val == val) {
res = res->next;
}
return res;
}
所以thisPtr = thisPtr->next;
成為thisPtr = nextDifferent(*thisPtr);
。
編輯
您的循環應類似於:
for (thisPtr = this->head, otherPtr = otherList.head;
thisPtr != NULL && otherPtr != NULL; )
{
if (thisPtr->val < otherPtr->val)
{
newList.AddToTail(thisPtr->val);
thisPtr = nextDifferent(*thisPtr);
}
else if (otherPtr->val < thisPtr->val)
{
newList.AddToTail(otherPtr->val);
otherPtr = nextDifferent(*otherPtr);
} else { // they are equal
newList.AddToTail(otherPtr->val);
otherPtr = nextDifferent(*otherPtr);
thisPtr = nextDifferent(*thisPtr);
}
}
while (otherPtr != NULL)
{
newList.AddToTail(otherPtr->val);
otherPtr = nextDifferent(*otherPtr);
}
while (thisPtr == NULL)
{
newList.AddToTail(thisPtr->val);
thisPtr = nextDifferent(*thisPtr);
}
由於列表按降序排列並且新列表也按降序排列,因此下面的步驟將起作用。
在將下一個元素添加到新列表之前,只需添加一個檢查:
if ( newNodeValue < lastAddedNodeValue )
//only then add to list.
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.