允许在单链表 C++ 上进行合并排序时出现重复项
我现在对此感到非常恼火。我正在为大学学习合并排序,并且正在经历这个 合并排序 我在网上找到的。但是,我似乎没有得到重复项,而且我想要重复项。其内容如下,但我已经对此进行了评论,这使得排序无法正常工作。有什么办法可以保留副本吗?如果您能让答案简单明了,我将不胜感激。谢谢
else
{
// Both are equal.
// Arbitraritly chose to add one of them and make
// sure you skip both!
if(c == NULL)
{
c = a;
}
else
{
c->next = a;
c = c->next;
}
a = a->next;
b = b->next;
}
I'm getting really annoyed with this now. I am learning merge sort for univeristy and am going through this merge sort I found on the net. However, I seem to NOT be getting duplicates and I want duplicates. Its this bit as follows but I've commented that bit out and stuff and it made the sort not work properly. Is there any way I could keep the duplicates? I'd appreciate if you could keep the answers simple. Thank you
else
{
// Both are equal.
// Arbitraritly chose to add one of them and make
// sure you skip both!
if(c == NULL)
{
c = a;
}
else
{
c->next = a;
c = c->next;
}
a = a->next;
b = b->next;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我认为线索就在代码中的注释中:“确保你跳过两者”。通过增加两个列表指针,您可以向输出添加一个元素,但跳过两个输入元素。所以只增加一个指针。然后,另一个元素将在下一次迭代时移至输出列表中。
I think the clue is in the comment in the code: "make sure you skip both". By incrementing both list pointers, you're adding one element to the output, but skipping two input elements. So only increment one pointer. Then, the other element will be moved into the output list on the next iteration.
如果您想保留重复项,请将两者都添加到链表
c
中。现在您只需将一个(即a
或b
)附加到链接列表中。因此,将您的代码更改为如下所示:
还要注意一点:具有重复项的排序列表的最终头将在
a
中开始,因为到该算法结束时c 将指向列表的末尾,该算法实际上是修改
a
和b
节点的指针(即c
> 不是一个带有新节点的新链表)。If you want to keep the duplicates, then add both to the linked list
c
. Right now you're only appending one (i.e.,a
orb
) to the linked list.So change your code to look like this:
One more note: the final head of the sorted list with duplicates will have its starting point in
a
, since by the end of this algorithmc
will be pointing to the end of the list, and this algorithm is actually modifying the pointers of thea
andb
nodes (i.e.,c
is not a new linked list with new nodes).您可以消除第三种情况(代码中列出的当前 else 块),并将第二种情况从
a > 更改为b
到else
- 现在它将处理a >= b
的任何情况,并且始终将a
放在前面排序后的列表。You can eliminate the third case (the current else block listed in the code), and change the second case from
a > b
toelse
- it will now be handling any case wherea >= b
, and will always placea
first in the sorted list.