繁体   English   中英

插入排序调试帮助

[英]Insertion sort debug help

以下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/

如果您的意图是真正修改输入指针list以指向此函数内部分配的内存,则需要将该函数声明为

static int insertSort (linkedlist **list)

然后返回sorted后的新建列表,如下所示:

*list = &sorted;

就目前而言,对destroylist的调用释放了条目中list内容,但分配仅修改输入指针的本地副本

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

list = &sorted;

在函数外的效果完全为零,但此行:

  destroythis (list);

确实释放了条目list所拥有的内存。 因此,返回后,您的输入指针现在将访问一个空列表。

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

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