helllo helllo - 3 months ago 8
C++ Question

Why can't I print more than one string?

I can print one string. But when I try to add two strings it only prints the first string? curr is the beginning of the linked list. If I add one country and tell the program to print it will print the country with the information. However if I add two countries, It will only print the first country.

void LinkedList::printList()
{
curr = head;
while (curr)
{
cout << "Country Name: " << curr->name << ", " << "Gold: " << curr->
gold << ", " << "Silver: " << curr->silver << ", " << "Bronze: " << curr->bronze << "\n";
curr = curr->next;
}
}

bool LinkedList::addCountry(string newName, int gold, int silver, int bronze) {
if (head == NULL)// Adding first element
{
head = new struct Country;
if (head == NULL) return false; // could not create head linked list country
head->name = newName;
head->gold = gold;
head->silver = silver;
head->bronze = bronze;
head->next = NULL;
return true;
} else {
curr = head;
while (curr) {
curr = curr->next;
}
curr = new struct Country;
if (curr == NULL)
return false;
curr->name = newName;
curr->gold = gold;
curr->silver = silver;
curr->bronze = bronze;
curr->next = NULL;
return true;
}
}

Answer

printList is correct. But in addCountry the last element must point to the new element which was just inserted. For example:

bool LinkedList::addCountry(string newName, int gold, int silver, int bronze) 
{
    Country *newNode = new Country;
    newNode->name = newName;
    newNode->gold = gold;
    newNode->silver = silver;
    newNode->bronze = bronze;
    newNode->next = NULL;

    if (head == NULL)// Adding first element
    {
        head = newNode;
    }
    else 
    {
        Country *prev = head;
        while (prev)
            prev = prev->next;
        prev->next = newNode;
    }
    return true;
}

Also in C++ you can simple write new Country, it doesn't need struct keyword.

Comments