2016-08-28 253 views
1

我可以打印一個字符串。但是當我嘗試添加兩個字符串時,它只打印第一個字符串? 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; 
    } 
} 
+2

你確定第二個正確結束在列表中? – tkausl

+0

@AndrewL不,你不需要那個。 –

+0

我們可以看到如何將字符串添加到鏈接列表中? –

回答

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關鍵字。

+0

當我嘗試添加第二個國家時,它說程序停止工作。感謝您儘量簡化問題。 – helllo

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; 
    }; 
    }; 
相關問題