Пример #1
0
int SLRemove(SortedListPtr list, void *newObj) {
  Node *curr;
  Node *prev;
  curr = list->front;
  prev = NULL;
  // Search through the list for the node to be removed.
  while (curr != NULL) {
	// If found remove it from the list.
    if (list->compareFunct(curr->content, newObj) == 0) {
		// If it is in the front of the list.
		if (prev == NULL) {
			list->front = curr->next;
			curr->ptrCounter--;
			if (list->front != NULL) {
				list->front->ptrCounter++;
			}
		}
		else {
			prev->next = curr->next;
			curr->ptrCounter--;
			if (prev->next != NULL) {
				prev->next->ptrCounter++;
			}
		}
		// If its pointer counter falls to zero, delete it.
		if (curr->ptrCounter <= 0) {
			list->destroyFunct(curr->content);
			if (curr->next != NULL) {
				curr->next->ptrCounter--;
			}
			free(curr);
		}
      return 1;
    }
    /*
     * If the current content is larger than the content to be removed, move on.
     * The node to be removed must lie after this node.
     */
    else if (list->compareFunct(curr->content, newObj) > 0) {
      prev = curr;
      curr = curr->next;
    }
    /*
     * If the current content is less than the content to be removed, simply
     * stop. The content to be removed doesn't exist in the list. Return 0.
     */
    else {
      return 0;
    }
  }
  // Otherwise you couldn't find the element in the list.
  return 0;
}
Пример #2
0
/*
 * SLDestroy destroys a list, freeing all dynamically allocated memory.
 *
 * You need to fill in this function as part of your implementation.
 */
void SLDestroy(SortedListPtr list) {
  Node *temp;
  // Runs through the entire list, deleting the front node every time through.
  while (list->front != NULL) {
    temp = list->front;
    list->front = list->front->next;
    // Destroying the content pointed to by the node and then freeing the node.
    list->destroyFunct(temp->content);
    free(temp);
  }
  // Freeing the list after we destroy all the nodes.
  free(list);
}