Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>You need to need to break down the function of (say) the <code>insert</code> method.</p> <ul> <li><p>The new node will (typically) be inserted <em>between</em> two nodes ... except when you end up inserting at the start and end of the list.</p></li> <li><p>The local variable initialization sets things up so that we start looking at the beginning of the loop. The <code>prev</code> variable will point to the node <em>before</em> the insertion point. The <code>curr</code> variable will point to the node <em>after</em> the insertion point.</p></li> <li><p>The <code>while</code> loop finds the insertion point. It walks through the list nodes until it finds one that is greater than or equal <code>x</code>. The insertion point is <em>before</em> that node. If the list is empty (i.e. <code>head</code> is <code>null</code>), the insertion point is the start of the list. When it completes (including the case where it never runs), <code>prev</code> and <code>curr</code> will have the values needed for the final part ...</p></li> <li><p>The code after the while loop does the insertion, inserting the new node between the <code>prev</code> node and the <code>curr</code> node. If <code>prev</code> is <code>null</code>, it has to handle things differently.</p></li> </ul> <hr> <p>So to answer your question:</p> <blockquote> <p>But which code makes curr not null then?</p> </blockquote> <p>No code does that. It does not need to be not null. </p> <p>At the point you are acttually doing the insertion, <code>curr</code> is the node after the insertion point. If you are inserting at the end of the list (or into an empty list), there is no node after the insertion point, and <code>curr</code> will (and should) be <code>null</code>.</p> <hr> <p>Insertion into singly linked lists is a little bit tricky to get your head around, but the key thing to remember is that any algorithm needs to find and update the node <em>before</em> the place you want to insert the new node. The same goes for deletion.</p>
    singulars
    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.
    1. This table or related slice is empty.
    1. VO
      singulars
      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