remove item return item to be removed; NULL if item does not exist
| 294 | // remove item |
| 295 | // return item to be removed; NULL if item does not exist |
| 296 | void *Heap_remove_item |
| 297 | ( |
| 298 | heap_t *hp, |
| 299 | const void *item // the item that is to be removed |
| 300 | ) { |
| 301 | int idx = __item_get_idx(hp, item); |
| 302 | |
| 303 | if(idx == -1) { |
| 304 | return NULL; |
| 305 | } |
| 306 | |
| 307 | // swap the item we found with the last item on the heap |
| 308 | void *ret_item = hp->array[idx]; |
| 309 | hp->array[idx] = hp->array[hp->count - 1]; |
| 310 | hp->array[hp->count - 1] = NULL; |
| 311 | |
| 312 | hp->count -= 1; |
| 313 | if(idx < hp->count) { |
| 314 | if(hp->cmp(hp->array[idx], ret_item, hp->udata) < 0) { |
| 315 | // replacement > removed |
| 316 | // ensure heap property |
| 317 | __pushdown(hp, idx); |
| 318 | } else { |
| 319 | // replacement <= removed |
| 320 | // ensure heap property |
| 321 | __pushup(hp, idx); |
| 322 | } |
| 323 | } |
| 324 | |
| 325 | return ret_item; |
| 326 | } |
| 327 | |
| 328 | // test membership of item |
| 329 | // return 1 if the heap contains this item; otherwise 0 |