合并两个链表,没有重复
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.
相关文章:
- 如何使用模板元编程在自由函数C++链接两个不相关的类
- 链接两个使用 c++ 构建的库_static
- 当我链接两个静态C++库时,我可以在两个主函数库中有两个主要功能吗?
- 在链接到两个 exe 的 dll 中共享全局变量
- 如何链接两个LLVM位码模块?
- 在没有额外代码的情况下链接两个独立类的最通用方法是什么?
- 在 Linux 上的 Visual Studio 中链接两个项目
- 在同一C++项目中链接两个不同版本的 protobuf 库
- 如何链接两个ArUco标记的姿势
- CMakeLists配置以链接两个C++项目
- 如何静态链接到两个版本的 xerces-c(或任何与此相关的库)
- Xcode 不链接两个结构
- 如何在 C/C++ 中链接两个 .so
- 链接两个具有相同函数签名的强函数符号的结果使用 G++ 以及原因
- 在 Visual Studio 解决方案中链接两个项目
- 链接两个枚举类型成员
- OpenGL - 链接两个纹理不起作用
- 我如何使用cmake链接两个库到我的程序
- 当链接到两个第三方共享库时,c++程序崩溃
- 在链接两个对象文件时,使用#ifndef防止定义一个函数两次