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

示例代码:插入排序

原代码

<br />
struct node *insert(struct node *node, struct node *list) {<br />
  struct node *cur = list;</p>
<p>  if(!cond(cur, node)){<br />
      node-&gt;next = list;<br />
      return node;<br />
  }</p>
<p>  while (cur-&gt;next != NULL &amp;&amp; cond(cur, node))<br />
      cur = cur-&gt;next;</p>
<p>  node-&gt;next = cur-&gt;next;<br />
  cur-&gt;next = node;<br />
  return list;<br />
}<br />

修改后

<br />
struct node *insert(struct node *node, struct node *list) {<br />
  struct node **cur = &amp;list;</p>
<p>  while (*cur != NULL &amp;&amp; cond(*cur, node))<br />
    cur = &amp;(*cur)-&gt;next;</p>
<p>  node-&gt;next = *cur;<br />
  *cur = node;</p>
<p>  return list;<br />
}</p>
<p>

发表评论

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