Untitled

 avatar
unknown
c_cpp
a year ago
1.6 kB
3
Indexable
int compareCollectibles(void *v1, void *v2) {
  // Cast void pointers to COllectible pointers...
  Collectible *c1 = (Collectible*) v1;
  Collectible *c2 = (Collectible*) v2;
  // Compare collectible values
  if (c1->value < c2->value) {
    return -1;
  } else if (c1->value > c2->value) {
    return 1;
  }
  }
  // If collectible values were equal, compare names:
  const int strcmpResult = strcmp(c1->name, c2->name);
  if (strcmpResult < 0) {
    return -1;
  } else if (strcmpResult > 0) {
    return 1;
  } else {
    return 0;
  }
}

int insertCollectibleItem(ListNode **theList, void *data) {
  // Allocate space for a new list node...
  ListNode *newNode = malloc(sizeof(ListNode));
  // Set the data pointer to point to given parameter's address
  newNode->data = data;

  // If List is empty, add newNode to head and return
  if (*theList == NULL) {
    newNode->next = NULL;
    *theList = newNode;
    return 0;
  }

  // Traverse the list, finding the correct place to insert the new item
  ListNode *previousNode = NULL;
  ListNode *currentNode = *theList;

  // Get to position in list where the node is <= the currentNode
  while (currentNode != NULL && compareCollectibles(newNode->data, currentNode->data) > 0) {
    previousNode = currentNode;
    currentNode = currentNode->next;
  }

  // If newNode is <= list head...
  if (previousNode == NULL) {
    *theList = newNode;
    newNode->next = currentNode;
  }
  // If newNode is somewhere in the middle of the list
  //    - Should handle end of list, as currentNode will be NULL
  else {
    previousNode->next = newNode;
    newNode->next = currentNode;
  }

  return 0;
}
Editor is loading...
Leave a Comment