Exemplo n.º 1
0
void inventory::AddItem(const item& newItem) {
    // We start by checking the weight to see if it will overload us.
    // If so, we don't do anything and can immediately return.

    if(newItem.getWeight() + _weight > _maxWeight) {
        newItem.printFailure();
        return;
    }

    itemNode *newNode = new itemNode;
    
    if(newNode) {
        newNode->setItem(newItem);
        itemNode *currentNode = _head;
        itemNode *previousNode = NULL;

        // Go to the first node that is greater than newItem.
        // previousNode will either be NULL, (in which case it's
        // at the head of the list) equal to newItem,
        // (in which case it will be incremented)
        // or less than newItem (in which case newNode will be
        // put between previousNode and currentNode).

        while(currentNode && newItem >= currentNode->getItem()) {
            previousNode = currentNode;
            currentNode = currentNode->getNext();
        }

        if(previousNode == NULL) {
            newNode->setNext(_head);
            _head = newNode;
            addWeightAndCount(newNode, newItem);
        }

        else if(newItem == previousNode->getItem()) {
            addWeightAndCount(previousNode, newItem);
            delete newNode;
        }

        else {
            previousNode->setNext(newNode);
            newNode->setNext(currentNode);
            addWeightAndCount(newNode, newItem);
        }
    }

    return;
}