Note that there are some explanatory texts on larger screens.

plurals
  1. POLinked List: Is this solution good?
    text
    copied!<p>I was looking for a way to avoid starting from the head of the list each time I want to find a node, so I thought of assigning indexes to nodes, keeping a pointer to a random (not exactly random; see below) node and then finding the pointer that's closest to the index I want to find. Allow me to explain with code:</p> <pre><code>// head and last are pointers to the first and last items of a doubly-linked list // current is a pointer that will change over time. It's used as a temporary pointer template &lt;class T&gt;a Node&lt;T&gt;* List&lt;T&gt;::get_closest(Node&lt;T&gt; node, int&amp; difference) { int curr_to_i = current-&gt;index - node-&gt;index; int last_to_i = last-&gt;index - node-&gt;index; Node* closest = node-&gt;index &lt; abs(curr_to_i) ? head : current; closest = closest-&gt;index &lt; abs(last_to_i) ? closest : last; difference = closest-&gt;index - node-&gt;index; return closest; } /* * This functions adds a node with the given value to the given index. The node at that * index and all the following are moved, and the new node is inserted before them. */ template &lt;class T&gt; bool List&lt;T&gt;::add(T value, int index) { if (index &lt; 0) { //Invalid index return false; } else if (index == last-&gt;index +1) { push(value); return true; } else if (index &gt; 0) { Node* new_n = new Node; new_n-&gt;value = value; new_n-&gt;index = index; int difference; Node* closest = get_closest(new_n, difference); if (difference &lt; 0) { for (int i = 0; i &lt; abs(difference); i++) { current = current-&gt;previous; } } else if (difference &gt; 0) { for (int i = 0; i &lt; abs(difference); i++) { current = current-&gt;next; } } /* current now points to the node we want to move */ new_n-&gt;previous = current-&gt;previous; new_n-&gt;next = current; current-&gt;previous-&gt;next = new_n; current-&gt;previous = new_n; if (index == 0) { root = new_n; } new_n = new_n-&gt;next; while (new_n != null) { new_n-&gt;index++; new_n = new_n-&gt;next; } return true; } } </code></pre> <p>Is this more efficient than starting from the head and advancing forward a number of times?</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