Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p><strong>For <code>insert</code>:</strong></p> <p>About these lines:</p> <pre><code>while(head-&gt;next-&gt;priority &gt;= priority) head = head-&gt;next; </code></pre> <ul> <li><p>If <code>head</code> is <code>NULL</code>, that's not going to work. This may not actually be a problem if <code>head</code> can never be <code>NULL</code> for whichever reason (e.g. it has a dummy element as gruszczy mentioned).</p></li> <li><p>You're changing <code>head</code>, thus you're getting rid of the first few elements every time you insert. You probably need a temp variable.</p></li> <li><p>You need to also have a <code>NULL</code> check in case you reach the end of the list.</p></li> </ul> <p>So, we get:</p> <pre><code>struct process *temp = head; while (temp-&gt;next != NULL &amp;&amp; temp-&gt;next-&gt;priority &gt;= priority) temp = temp-&gt;next; </code></pre> <p><strong>For <code>pop</code>:</strong></p> <p>If the first element isn't a dummy element, then you should be returning the ID of <code>head</code>, not <code>head-&gt;next</code> (and you were trying to return a value of an already freed variable - this is undefined behaviour).</p> <pre><code>if (head == NULL) return -1; int id = head-&gt;id; struct process *temp = head; head = head-&gt;next; free(temp); return id; </code></pre> <p><strong>For <code>popId</code>:</strong></p> <ul> <li><p>You're checking <code>ptr</code>'s ID, but, if it's the one we're looking for, you're removing the next element rather than <code>ptr</code>. You should be checking the next one's ID.</p></li> <li><p><code>head == NULL</code> would again need to be a special case.</p></li> <li><p>The <code>free</code> should be in the if-statement. If it isn't, you need to cater for it not being found or finding multiple elements with the same ID.</p></li> <li><p>You should break out of the loop in the if-statement if there can only be one element with that ID, or you want to only remove the first such element.</p></li> </ul> <p>I'll leave it to you to fix, but here's a version using double-pointers.</p> <pre><code>void popId(int id) { struct process **ptr = &amp;head; while (*ptr != NULL) { if ((*ptr)-&gt;id == id) { struct process *temp = *ptr; *ptr = (*ptr)-&gt;next; free(temp); } else { prt = &amp;(*ptr)-&gt;next; } } } </code></pre> <p>Note that the above code doesn't break out of the loop in the if-statement. This can be added if you're guaranteed to only have one element with some given ID in the list, or you want to just delete the first such element.</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