コード例 #1
0
//**************************************************
// The insertNode function inserts a node with
// countryIn copied to its country member.
//**************************************************
void CountryList::insertNode(Country countryIn)
{
  ListNode *newNode;             // A new node
  ListNode *nodePtr;             // To traverse the list
  ListNode *previousNode = NULL; // The previous node

                                 // Allocate a new node and store the country there.
  newNode = new ListNode;
  newNode->SetCountry(countryIn);

  previousNode = head;
  nodePtr = head->GetNextListNode();
  // Find the location of the new node in the sorted list
  while (nodePtr != NULL && strcmp(nodePtr->GetCountry().GetCode(), countryIn.GetCode()) < 0) {
    previousNode = nodePtr;
    nodePtr = nodePtr->GetNextListNode();
  }
  // Update links and counter
  previousNode->SetNextListNode(newNode);
  newNode->SetNextListNode(nodePtr);
  cnt++;
}
コード例 #2
0
//**************************************************
// The deleteNode function searches for a node
// with code as its code. The node, if found, is
// deleted from the list and from memory.
// It returns an error code
//      -1 represents an empty list
//      0 means the country was not found
//      1 means the country was deleted
//**************************************************
int CountryList::deleteNode(const char* code)
{
  ListNode *nodePtr;       // To traverse the list
  ListNode *previousNode = NULL;  // To point to the previous node

                           // check if list is empty
  if (cnt == 0)
    return -1; // -1 for empty list

  nodePtr = head->GetNextListNode();
  // Search for the node to be deleted from the list
  while (nodePtr != NULL && strcmp(nodePtr->GetCountry().GetCode(), code) != 0) {
    previousNode = nodePtr;
    nodePtr = nodePtr->GetNextListNode();
  }
  if (nodePtr) { // found
    previousNode->SetNextListNode(nodePtr->GetNextListNode());
    delete nodePtr;
    cnt--;
    return 1; // 1 for success
  }
  return 0; // 0 for not found
}