我可以打印一个字符串。但是当我尝试添加两个字符串时,它只打印第一个字符串? 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;
}
}
答案 0 :(得分:1)
@Barmak Shemirani是对的。我想如果你有一个尾巴会员会更好:
class LindedList
{
public:
LindedList()
{
tail=head=curr=NULL;
};
Country* head;
Country* curr;
Country* tail;
void printList()
{
curr = head;
while (curr)
{
cout << "Country Name: " << curr->name << ", " << "Gold: " << curr->
gold << ", " << "Silver: " << curr->silver << ", " << "Bronze: " << curr->bronze << "\n";
curr = curr->next;
}
};
bool addCountry(string newName, int gold, int silver, int bronze)
{
curr = new Country;
if (curr == NULL)
return false;
curr->name = newName;
curr->gold = gold;
curr->silver = silver;
curr->bronze = bronze;
curr->next = NULL;
if (head == NULL)
{
head = curr;
tail=curr;
} else
{
tail->next=curr;
tail=curr;
}
return true;
};
};
答案 1 :(得分:0)
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
个关键字。