Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Yes, you are right that there's a bug in the function - <code>cur-&gt;next</code> isn't updated correctly in all cases.</p> <p>I personally find the local variable names <code>tmp</code> and <code>next</code> not particularly helpful and actively confusing in the case of <code>next</code>. Those names make it hard for me to keep track in my head of what's going on as I read through the function.</p> <p>I find that the names <code>node1</code>, <code>node2</code>, and <code>node3</code> work better to for me to keep a mental picture of which node is being manipulated. I wouldn't be surprised if other people disagree, though.</p> <p>Here's a reworked version of the function that I find more readable, and more importantly that I believe is correct.</p> <pre><code>void swap (struct list **head) { struct list *node1 = *head; struct list *node2 = node1 ? node1-&gt;next : NULL; // handle degenerate cases if (!node2) { // no elements or only one element on the list // nothing to do... return; } // fix-up list head to what will be the new first node on list *head = node2; // while there are at least 2 more elements to be swapped while (node1 &amp;&amp; node2) { struct list* node3 = node2-&gt;next; // get a pointer to the node that will be the remainder of the // list after the remainder of the list is processed. // // This will be NULL, node3, or 'node4' depending on whether // there are 0 , 1 or 2+ nodes following node1 and node2 struct list* remainder = (node3 &amp;&amp; node3-&gt;next) ? node3-&gt;next : node3; node1-&gt;next = remainder; node2-&gt;next = node1; // prepare pointers to the next two nodes to be swapped node1 = node3; node2 = node3 ? node3-&gt;next : NULL; } return; } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload