Note that there are some explanatory texts on larger screens.

plurals
  1. POC: Creating a Queue in Ascending Order
    text
    copied!<p>I'm working on a problem where the objective is to create a linked list (a queue) in ascending order regardless of what order it's entered. I've been able to construct my assignment so that it enters data and pushes it onto a stack and correctly pops the first item from the queue (this is the code below) but I cannot seem to get a working algorithm to construct the queue in ascending order. </p> <p>I reworked my algorithm by using a second function within my addItem to find the correct location of any newly added structure so it now properly handles sorting. My reworked code is below. </p> <pre><code>void addItemToQueue(int *identification, float *houlyrate) { struct Employee *locateInsertionPoint(int *); struct Employee *newAddress, *here; newAddress = (struct Employee *) malloc(sizeof(struct Employee)); // Allocate Space for the new structure if (newAddress == (struct Employee *) NULL) { // Display Error message and terminate if allocation fails printf("\nERROR: Failed to allocate memory for this structure.\n"); free(queueOut); // Free the Queue in the event memory fails to allocate new space exit(1); } if (queueOut == NULL) { // Does queue exist newAddress-&gt;nextAddress = NULL; queueOut = newAddress; } else if (*identification &lt; queueOut-&gt;idnum) { // Is the new ID Number less than the old ID Number newAddress-&gt;nextAddress = queueOut; queueOut = newAddress; } else { here = locateInsertionPoint(identification); // Use locateInsertionPoint() function to find proper place for new ID newAddress-&gt;nextAddress = here-&gt;nextAddress; here-&gt;nextAddress = newAddress; } newAddress-&gt;idnum = *identification; // Make new structure id num equal to the passed id num newAddress-&gt;hourlyrate = *houlyrate; // Make new structure payrate equal to the passed payrate } struct Employee *locateInsertionPoint (int *idnum) { struct Employee *one, *two; one = queueOut; two = one-&gt;nextAddress; if (two == NULL) { // Check if There is only 1 item return one; } while (1) { // LOOP if (*idnum &lt; two-&gt;idnum) { // Is the new ID less than current ID break; } else if (two-&gt;nextAddress == NULL) { // IF Not, is the next address NULL one = two; break; } else { // IF Not, shift pointers to read next set one = two; two = one-&gt;nextAddress; } } return one; } </code></pre>
 

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