合并单链表上的排序
Merge Sort on singly linked list
我在C++中的合并排序代码有问题。我不知道为什么,但是当我从Merge_Sort调用它们时,这些函数无法正常工作。它们单独工作。
当我输入这样的列表时:H->1->2->8->4->7->6->33->NULL
作为一个排序列表,我得到这样的东西:H->33->4->6->NULL。
void Split(node *&H, node *&h1, node *&h2)
{
if (H != NULL)
{
node *P = H;
bool check = 0;
while (H != NULL)
{
P = H;
H = H->next;
if (check) {
AddLastNode(h2,P);
}
else
{
AddLastNode(h1, P);
}
check=!check;
}
}
}
void Merge(node *&H, node *&h1, node *&h2)
{
node *p1=h1, *p2=h2;
node *temp = H;
while (h1!=NULL && h2!=NULL)
{
p1 = h1;
p2 = h2;
if (p1->val < p2->val)
{
h1 = h1->next;
temp = p1;
}
else
{
h2 = h2->next;
temp = p2;
}
temp->next = H;
H = temp;
}
if (h1 == NULL)
{
temp = h2;
temp->next = H;
H = temp;
}
else if (h2 == NULL)
{
temp = h1;
temp->next = H;
H = temp;
}
}
void Merge_Sort(node *&H)
{
node *h1, *h2;
if (H && H->next)
{
h1 = h2 = NULL;
Split(H, h1, h2);
Merge_Sort(h1);
Merge_Sort(h2);
Merge(H, h1, h2);
}
}
问题出在递归调用Merge_Sort
中。你在指针上引用它,所以最后它们变成了 1 长度,其他数据丢失。我认为这是糟糕的算法。使用 STL 容器和算法可以更轻松地做到这一点。使用std::list
作为容器,将其分开。然后在单独的容器上使用列表方法sort
,并在新容器或h1,h2之一上进行merge
。这是我的合并算法代码:
#include <iostream>
#include <string>
#include <algorithm>
#include <list>
void TraceList( const std::list<int32_t>& lst, const std::string& title = "" )
{
if ( !title.empty() )
{
std::cout << title << std::endl;
}
std::copy(lst.begin(), lst.end(), std::ostream_iterator<int16_t>(std::cout, ","));
std::cout << std::endl;
}
int main()
{
//Input test data. You can use here your input code
const uint32_t SIZE_START = 10;
int16_t ArrInputData[SIZE_START] = {4, 45, 12, 78, 11, 17, 2, 58, 79, 10 };
std::list<int32_t> StartList;
std::copy(ArrInputData, ArrInputData + SIZE_START, std::back_inserter(StartList));
//Separate input data on parts
std::list<int> h1;
std::list<int> h2;
bool CounterFlag = true;
std::for_each(StartList.begin(), StartList.end(), [&CounterFlag, &h1, &h2]( int16_t val )
{
CounterFlag ? h1.push_back(val) : h2.push_back(val);
CounterFlag = !CounterFlag;
});
//Sort separated parts
h1.sort();
h2.sort();
TraceList(h1, "H1 list:");
TraceList(h2, "H2 list:");
//Merge separated
std::list<int32_t> FinalMergedList = h1; //Copy one of separated to new list
FinalMergedList.merge(h2);
TraceList(FinalMergedList, "MergeFinal list:");
return 0;
}
结果是:
H1 list:
2,4,11,12,79,
H2 list:
10,17,45,58,78,
MergeFinal list:
2,4,10,11,12,17,45,58,78,79,
Program ended with exit code: 0
如果您喜欢我的解决方案std::list
那么您也应该考虑其他容器。 当你插入尾巴和头部之间时,std::list
很好,但在排序方面却很糟糕。可能您应该使用任何具有随机访问功能的容器,它们的排序速度更快,例如 std::vector
.
相关文章:
- 为什么在排序链表上的这种合并实现总是将两个列表都设置为 NULL,而只有一个应该设置一个列表?
- 合并两个排序链表时运行时出错
- 在 C++ 中合并两个排序链表
- 在排序链表中插入结构并将其写入二进制文件
- C++:按数字排序链表错误
- 家庭作业的排序链表程序中的分段错误
- 删除已排序链表中的值
- 排序链表-移动节点还是交换数据成员
- 单排序链表-无限循环
- 插入排序链表c++
- 冒泡排序链表C++
- 将元素添加到排序链表C++时出现问题
- 升序排序 - 链表
- 气泡排序链表不排序
- C++ 中的排序链表不会插入
- 删除具有重复相同值的已排序链表中的重复值
- 未排序链表实现检查完毕
- 插入排序链表c++
- c++中从排序链表中删除重复值节点的方法
- 排序链表和addSorted函数问题