我目前正在实施链接列表(在我的休假期间!)并且我发现我的功能结构如下:
void traverseList(node *head){
if(head != 0){
while(head->next !=0){
cout << head->data << endl;
head = head->next;
}
//one extra for the node at the end
cout << head->data << endl;
}
}
我想知道有没有人知道如何消除“一次额外”的电话?
答案 0 :(得分:5)
您的功能可以大大简化为:
void traverseList(node *head)
{
for(node * iterator = head; iterator; iterator = iterator->next)
{
cout << iterator->data << endl;
}
}
答案 1 :(得分:3)
改变这个:
if(iterator != 0){
while(iterator->next !=0){
cout << iterator->data << endl;
iterator = iterator->next;
}
//one extra for the node at the end
cout << iterator->data << endl;
}
到此:
while(iterator != 0) {
cout << iterator->data << endl;
iterator = iterator->next;
}