Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>I would have made a prepend function, and done the following:</p> <pre><code>struct node* prepend(struct node* root, int value) { struct node* new_root = malloc(sizeof(struct node)); new_root-&gt;next = root; return new_root; } struct node* reverselist(struct node* inlist) { struct node* outlist = NULL; while(inlist != NULL) { struct node* new_root = prepend(outlist, inlist-&gt;value); outlist = new_root; inlist = inlist-&gt;next; } return outlist; } </code></pre> <p>Have not tested this, but guess you grasp the idea of it. Might be just your variable names, which don't describe anything, but I think this approach is cleaner, and easier to understand what actually happens.</p> <p>EDIT:</p> <p>Got a question why I don't do it inplace, so I'll answer it here:</p> <ol> <li>Can you do it inplace? Are you sure you don't wish to keep the original list?</li> <li>Do you need to do it inplace? Is the malloc to time consuming/is this a performance critical part of your code? Remember: premature optimization is the root of all evil.</li> </ol> <p>Thing is, this is a first implementation. It should work, and not be optimized. It should also have a test written before this implementation is even thought of, and you should keep this slow, un-optimized implementation until the test passes, and you have proved that it's to slow for your use!</p> <p>When you have a passing unit test, and proven the implementation to be to slow, you should optimize the code, and make sure it still passes the test, without changing the test.</p> <p>Also, is it necessary inplace operations which is the answer? What about allocating the memory before reverting it, this way you only have one allocation call, and should hopefully get a nice performance boost.</p> <p>This way everyone is happy, you have a cleaner code and avoid the risk of having Uncle Bob showing up at your door with a shotgun.</p>
 

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