我在看http://publications.gbdirect.co.uk/c_book/chapter6/structures.html中的示例6.7
(为了方便贴在这里)

struct list_ele *
sortfun( struct list_ele *list )
{

      int exchange;
      struct list_ele *nextp, *thisp, dummy;

      /*
       * Algorithm is this:
       * Repeatedly scan list.
       * If two list items are out of order,
       * link them in the other way round.
       * Stop if a full pass is made and no
       * exchanges are required.
       * The whole business is confused by
       * working one element behind the
       * first one of interest.
       * This is because of the simple mechanics of
       * linking and unlinking elements.
       */

      dummy.pointer = list;
      do{
              exchange = 0;
              thisp = &dummy;
              while( (nextp = thisp->pointer)
                      && nextp->pointer){
                      if(nextp->data < nextp->pointer->data){
                              /* exchange */
                              exchange = 1;
                              thisp->pointer = nextp->pointer;
                              nextp->pointer =
                                      thisp->pointer->pointer;
                              thisp->pointer->pointer = nextp;
                      }
                      thisp = thisp->pointer;
              }
      }while(exchange);

      return(dummy.pointer);
}

我知道基本的想法,但我不能解释到底发生了什么。有人能更深入地解释一下排序函数中发生的事情吗?
一般问题:
为什么需要dummy.pointer = list;dummy然后在函数结束时返回,为什么列表仍然被排序?
这个评论是什么意思?

最佳答案

dummy是首先设置到列表开头的局部变量。临时变量thisp被设置为指向dummy,因此当它被更新时,dummy指向的内容也会被更新。因此,dummy.pointer最终将指向作为排序列表的新开头的元素。list仍将指向列表的原始开头,因此返回值以便可以更新头指针。
我认为他们混淆的意思是我们感兴趣的元素是nextp,而不是当前元素(或thisp)。也就是说,我们将列表中的下一个元素与当前元素进行比较,而不是将当前元素与前一个元素进行比较。我想这很让人困惑,但我真的不这么认为。
注:这是Bubble Sort。一个更好的排序算法是Merge Sort,实现在http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html

关于c - 排序单链列表-我不明白,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/10964129/

10-11 22:26
查看更多