【问题标题】:Insertion sort debug help插入排序调试帮助
【发布时间】:2011-05-02 04:38:40
【问题描述】:

以下 C 代码不起作用(它只是清除列表):

/* Takes linkedlist of strings */
static int insertSort (linkedlist *list) {
  linkedlist sorted;
  void *data;
  node *one, *two, *newnode;
  unsigned int comp, x;

  removeHeadLL (list, &data);
  initLL (&sorted);
  addHeadLL (&sorted, data);

  while (list->count) {
    removeHeadLL (list, &data);
    two = sorted.head;

    x = 0;
    for (comp = strcomp (data, two->data) ; comp > 1 && x < sorted.count ; x++) {
      one = two;
      two = two->next;
    }

    if (x) {
      newnode = malloc (sizeof(node));
      newnode->next = two;
      newnode->data = data;
      one->next = newnode;
    }
    else {
      addHeadLL(&sorted, data);
    }

    (sorted.count)++;
  }

  destroythis (list);
  list = &sorted;
  return 0;
}

完整上下文:http://buu700.res.cmu.edu/CMU/15123/6/

【问题讨论】:

  • "以下 C 代码不起作用:" - 咳咳!什么不起作用?
  • 对不起,我有点含糊,因为我有点着急。结果是我得到了一个空白的链表——虽然不知道会发生什么。

标签: c algorithm list sorting pointers


【解决方案1】:

如果你的意图真的是修改输入指针list指向这个函数内部分配的内存,那么你需要将函数声明为

static int insertSort (linkedlist **list)

然后像这样从sorted返回新建的列表:

*list = &sorted;

就目前而言,对destroylist 的调用会在入口处释放list 中的内容,但分配只会修改输入指针的本地副本

换句话说,在您的原始代码中,这一行:

list = &sorted;

在函数之外的效果完全为零,但是这一行:

  destroythis (list);

确实释放了 list 在进入时拥有的内存。所以返回后,你的输入指针现在访问一个空列表。

【讨论】:

    【解决方案2】:

    危险,威尔罗宾逊:未经测试的代码。

    struct list { char *datum; struct list *next; };
    typedef struct list *listptr;
    
    listptr insert(char *x, listptr xs) {  
    
      listptr result = xs;
      listptr *from = &result;
      listptr new = (listptr) malloc(sizeof(struct list));
    
      while (xs != null && strcmp(xs.datum, x) < 0) {
        from = &xs;
        xs = xs->next;
      }
    
      new.datum = x;
      new.next = xs;
      *from = new;
    
      return result;
    }
    
    listptr isort(listptr xs) {
      listptr result = null;
      for(; xs != null; xs = xs->next) {
        insert(xs.datum, result);
      }
      return result;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-04-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多