// insert an integer into correct place in a sorted list void IntListInsertInOrder(IntList L, int v) { struct IntListNode *n, *curr, *prev; assert(L != NULL); n = newIntListNode(v); L->size++; if (L->first == NULL) { // empty list case L->first = L->last = n; } else if (n->data <= L->first->data) { // smallest value case n->next = L->first; L->first = n; } else if (n->data >= L->last->data) { // largest value case L->last->next = n; L->last = n; } else { curr = L->first; while (curr && n->data > curr->data) { prev = curr; curr = curr->next; } n->next = curr; prev->next = n; } }
// apppend one integer to the end of a list void IntListInsert(IntList L, int v) { struct IntListNode *n; assert(L != NULL); n = newIntListNode(v); if (L->first == NULL) L->first = L->last = n; else { L->last->next = n; L->last = n; } L->size++; }
// insert an integer into correct place in a sorted list void IntListInsertInOrder(IntList L, int v, int w) { assert(L != NULL); struct IntListNode *curr; struct IntListNode *val = newIntListNode(v,w); int inserted = FALSE; if (L->size == 0) { L->first = val; L->last = val; } else if(L->size == 1) { if(val->data < L->first->data) { val->next = L->first; L->first = val; } else { L->last->next = val; L->last = val; } } else { if(val->data < L->first->data) { val->next = L->first; L->first = val; inserted = TRUE; } if (!inserted) { for (curr = L->first; curr->next != NULL; curr = curr->next) { if (curr->next->data > v) { inserted = TRUE; val->next = curr->next; curr->next = val; break; } } } if(!inserted) { L->last->next = val; L->last = val; } } L->size++; }