/* Program 12.2, p. 328 Insert into an ordered, singly linked list. The arguments are a pointer to the first node in the list, and the value to insert. */ #include #include #include "linkedlist.h" int insert (NODE_T **rootp, int new_value) { NODE_T *current; NODE_T *previous; NODE_T *new; /* get the pointer to the first node */ current = *rootp; previous = NULL; /* look for the right place by walking down the list until we reach a node whose value is greater than or equal to the new value */ while (current != NULL && current -> value < new_value) { previous = current; current = current -> next; } /* allocate a new node and store the new value in it */ new = (NODE_T *) malloc (sizeof (NODE_T)); if (new == NULL) return FALSE; new -> value = new_value; /* insert the node into the list */ new -> next = current; if (previous == NULL) *rootp = new; else previous -> next = new; return TRUE; }