简体   繁体   English

插入排序调试帮助

[英]Insertion sort debug help

The following C code doesn't work (it just clears the list): 以下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;
}

Full context: http://buu700.res.cmu.edu/CMU/15123/6/ 全文: http : //buu700.res.cmu.edu/CMU/15123/6/

If your intent is really to modify the input pointer list to point to the memory allocated inside this function, then you need to declare the function as 如果您的意图是真正修改输入指针list以指向此函数内部分配的内存,则需要将该函数声明为

static int insertSort (linkedlist **list)

and then return the newly-built list from sorted like so: 然后返回sorted后的新建列表,如下所示:

*list = &sorted;

As it stands, the call to destroylist frees up what is in list on entry, but the assignment only modifies a local copy of the input pointer. 就目前而言,对destroylist的调用释放了条目中list内容,但分配仅修改输入指针的本地副本

In other words, in your original code this line: 换句话说,在您的原始代码中此行:

list = &sorted;

has exactly zero effect outside the function, but this line: 在函数外的效果完全为零,但此行:

  destroythis (list);

does indeed free up the memory that was owned by list on entry. 确实释放了条目list所拥有的内存。 So after return, your input pointer now accesses an empty list. 因此,返回后,您的输入指针现在将访问一个空列表。

Danger, Will Robinson: untested code. 危险,威尔·罗宾逊:未经测试的代码。

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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM