Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>The short answer: Yes, <code>b-&gt;Next-&gt;Previous</code> is fine -- it's a <code>struct Node*</code>, just like the right hand side <code>b-&gt;Previous</code>.</p> <p>I think that your error lies with the handling of <code>Count</code>: It is incremented by <code>Add()</code>, but <code>Remove()</code> doesn't decrement it. In fact, as the list itself only needs to know whether it is empty or not, you can remove it and instead see if <code>a.First == NULL</code>. (Your <code>a.Count == 1</code> test can likewise be replaced with <code>a.First != NULL &amp;&amp; a.First-&gt;Next == NULL</code> test.)</p> <p>If you're promising <code>Count</code> in you API, you can add it back when you've got the list itself working. The same "remove-then-add-back" might be useful with <code>Total</code>. Think of both of these as caches.</p> <p>An even better solution would be to implement a circular list:</p> <pre><code>struct List { Node Anchor; //... }; List Create() { List l; l.Anchor.Next = l.Anchor.Previous = &amp;l; return l; } bool IsEmpty(List const* l) { // Both or neither point at 'l'. assert((l-&gt;Anchor.Next == l) == (l-&gt;Anchor.Previous == l)); return l-&gt;Anchor.Next == l; } // Add a node 'n' to some list after 'ln'. void AddAfter(Node* n, Node* ln) { n-&gt;Previous = ln; n-&gt;Next = ln-&gt;Next; n-&gt;Next-&gt;Previous = n-&gt;Previous-&gt;Next = n; } Node* Remove(Node* n) { n-&gt;Previous-&gt;Next = n-&gt;Next; n-&gt;Next-&gt;Previous = n-&gt;Previous; n-&gt;Next = n-&gt;Previous = n; // nice and proper return x; } </code></pre> <p>Now you longer need special cases for empty lists. I let <code>Remove()</code> return the node itself, to make it easy to either move nodes between lists (<code>AddAfter(Remove(somenode), &amp;otherlist.Anchor)</code>) or remove and delete notes (<code>free(Remove(somenode))</code>).</p> <p>One wart here is that my <code>Anchor</code> node now wastes space for data that never will be used -- but that is easily fixable.</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

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