我可以打印一个字符串。但是,当我尝试添加两个字符串时,它仅显示第一个字符串吗?curr是链接列表的开始。如果我添加一个国家/地区并告诉程序进行打印,它将打印该国家/地区的信息。但是,如果我添加两个国家,它将仅打印第一个国家。
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;
}
}
printList
是正确的。但是在addCountry
最后一个元素中必须指向刚刚插入的新元素。例如:
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
{
//find the last element currently in the list:
Country *last = head;
while (last->next)//<= ***** edited
last = last->next;
//set newNode as the new last element:
last->next = newNode;
}
return true;
}
同样在C ++中,您可以简单地编写new Country
,它不需要struct
关键字。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句