Skip to content

Simplify Do While Loop Checking for Null Pointer

An answer to this question on Stack Overflow.

Question

I have a really basic problem that I can't figure out. I'm using chaining with hash tables to store nodes that collide with each other. I used a do while loop to print the first node at least once, and continue to print the chained nodes if they exist. However, in order to traverse the chained list, I need to change the address of the node for the next loop. Any way I try writing this, I find myself repeating code, which I was trying to avoid by using this loop. Please help

do {
        cout << "Bid id: " << table.at(i)->bidId << " title: " << table.at(i)->title <<
        " fund: " << table.at(i)->fund << " amount: " << table.at(i)->amount << endl;
        if (table.at(i)->next!=nullptr){//check if first node has next node         
             table.at(i) = table.at(i)->next; //change address to the next pointer
        }// how do I avoid repeating my condition below?
    }
    while (table.at(i)->next!=nullptr);

Answer

You could try doing:

for(auto node = table.at(i)->next;node!=nullptr;node=node->next)
  cout << "Bid id: " << node->bidId << " title: " << node->title;

Where you may need to replace node = table.at(i)->next with an appropriate way of getting a link to the first entry.