合并两个链表,没有重复

Merging two linked lists with no duplication

本文关键字:链表 两个 合并      更新时间:2023-10-16

我想编写一个代码来合并两个链表,以便结果列表没有重复。这两个列表是有序的,但其中可能有重复项。生成的列表应存储在当前列表中。代码应运行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.