消除链接列表中的额外调用

Tom*_*aly 0 c++ linked-list

我正在实现一个链表(在我的休息时间!),我发现我有这样的结构的函数:

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;
}
}
Run Code Online (Sandbox Code Playgroud)

我想知道有没有人知道如何消除"一个额外的"电话?

Jam*_*lin 5

您的功能可以大大简化为:

void traverseList(node *head)
{
    for(node * iterator = head; iterator; iterator = iterator->next)
    {
        cout << iterator->data << endl;
    }
}
Run Code Online (Sandbox Code Playgroud)