创建一个接受linkedlist作为输入的合并排序

creating a merge sort that accepts linkedlist as an input

本文关键字:输入 排序 合并 linkedlist 一个 创建      更新时间:2023-10-16

以下是我的一些代码

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移动同样的操作。更不用说,如果列表中只有一个项,则leftright是未初始化的,并且循环的最后一行可能会导致取消引用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语句中,因此循环将退出。