Assuming list has been sorted already, insert new_link to keep the list sorted according to the same comparison function. Comparison function is the same as used by sort, i.e. uses double indirection. Time is O(1) to add to beginning or end. Time is linear to add pre-sorted items to an empty list.
| 144 | // indirection. Time is O(1) to add to beginning or end. |
| 145 | // Time is linear to add pre-sorted items to an empty list. |
| 146 | void ELIST2::add_sorted(int comparator(const void*, const void*), |
| 147 | ELIST2_LINK* new_link) { |
| 148 | // Check for adding at the end. |
| 149 | if (last == NULL || comparator(&last, &new_link) < 0) { |
| 150 | if (last == NULL) { |
| 151 | new_link->next = new_link; |
| 152 | new_link->prev = new_link; |
| 153 | } else { |
| 154 | new_link->next = last->next; |
| 155 | new_link->prev = last; |
| 156 | last->next = new_link; |
| 157 | new_link->next->prev = new_link; |
| 158 | } |
| 159 | last = new_link; |
| 160 | } else { |
| 161 | // Need to use an iterator. |
| 162 | ELIST2_ITERATOR it(this); |
| 163 | for (it.mark_cycle_pt(); !it.cycled_list(); it.forward()) { |
| 164 | ELIST2_LINK* link = it.data(); |
| 165 | if (comparator(&link, &new_link) > 0) |
| 166 | break; |
| 167 | } |
| 168 | if (it.cycled_list()) |
| 169 | it.add_to_end(new_link); |
| 170 | else |
| 171 | it.add_before_then_move(new_link); |
| 172 | } |
| 173 | } |
| 174 | |
| 175 | /*********************************************************************** |
| 176 | * MEMBER FUNCTIONS OF CLASS: ELIST2_ITERATOR |
nothing calls this directly
no test coverage detected