消除边界情况(链表操作)

示例代码:插入排序

原代码

struct node *insert(struct node *node, struct node *list) {
  struct node *cur = list;

  if(!cond(cur, node)){
      node->next = list;
      return node;
  }

  while (cur->next != NULL && cond(cur, node))
      cur = cur->next;

  node->next = cur->next;
  cur->next = node;
  return list;
}

修改后

struct node *insert(struct node *node, struct node *list) {
  struct node **cur = &list;

  while (*cur != NULL && cond(*cur, node))
    cur = &(*cur)->next;

  node->next = *cur;
  *cur = node;

  return list;
}

发表评论

电子邮件地址不会被公开。 必填项已用*标注