创建一个接受linkedlist作为输入的合并排序
creating a merge sort that accepts linkedlist as an input
以下是我的一些代码
listnode *mergesort(struct listnode *list){
struct listnode *L, *R, *head;
int i = 0;
head = list;
while (list->next != NULL){
if (i%2 == 0){ //it splits the linkedlist into 2 segments
//it adds the elements in the linked list
// alternatively.
//to a linked list R & L
L=list->next;
list->next = L->next;
i=i+1;
}
else{
R= list->next;
list->next = R->next;
i=i+1;
}
list = list->next;
}
MergeLists(mergesort(L),mergesort(R));
}
我不断地遇到分割错误,不知道问题出在哪里。
首先,您的"计数"是在计数为偶数时将left
移动一,在计数为奇数时对right
移动同样的操作。更不用说,如果列表中只有一个项,则left
和right
是未初始化的,并且循环的最后一行可能会导致取消引用null。
其次,您需要一些方法来标记left
列表的末尾,否则您的合并将一遍又一遍地执行相同的操作,直到溢出堆栈。
我们可以通过将左半部分的最后一个指针设置为NULL来实现这一点。请记住,MergeLists必须修复所有这些,才能再次创建一个好的列表。
试试这样的东西:
listnode *mergesort(listnode *list) {
listnode *left = list, *right = list, *prev, *end = list;
if (list == 0) { return list; }
// move right once for every two we move end, so that we divide the middle
while (end != 0) {
end = end->next;
prev = right; // keep track of the node before the start of right
right = right->next;
if (end != 0) {
end = end->next;
}
}
if (left->next == right) {
// TODO swap items if necessary
return left;
}
prev->next = 0; // split the list
left = mergesort(left);
right = mergesort(right);
// TODO join left and right by calling MergeLists or whatever
return left;
}
指针工作图:
prev->next = 0 removes -----|
v
list -> [1] -> [2] -> [3] -> [4] -> [5] -> [6]
left ----^ ^
right -------------------------|
我注意到两件事:1.int i=0;意味着我将永远是平等的。"i"是列表节点中的值吗?2.返回MergeLists(L,R);在while语句中,因此循环将退出。
相关文章:
- 是否有类似std::lower_bound的函数,而不需要排序/分区输入
- 使用STL对用户输入数组进行排序的错误有什么解决方案吗?
- 读取一组用户输入,按升序排序,然后打印结果
- 如何按升序对输入文件中的数字进行排序,并找到它们的范围和中值
- 如何从输入的文本文件中按姓氏字母顺序对图表进行排序?
- 切换输入用于排序算法
- 当输入向量称为储备金时,STD ::排序无法正常工作
- 根据输入文本对单词进行排序,具体取决于重复多少次
- 气泡排序问题不会更改输入阵列
- 无法让我的代码正确排序用户输入的数字数组(使用递归)
- 快速排序算法,一些特定输入序列的错误答案和分段错误
- 如何输入整数并将其从最高到最低排序
- 根据这些字符串输入在句子中的位置对这些字符串输入进行排序的更快方法是什么
- 合并排序 - 返回新数组,而不是将合并的数组复制到输入数组
- 如何输入字符串对容器进行排序
- 为什么大多数STL算法都需要将排序数据作为输入
- 当输入大小足够大时,合并排序崩溃
- 面试难题:用有限的记忆对输入的一百万个数字进行排序
- std::map 的排序顺序取决于输入值
- 按第一个值和第二个值将输入排序到一个链表中