ben
ben

Reputation: 137

Check for a value using LinkedList

void List::IsinList(int resnum){
    Node* temp = head;

while (resnum != temp->_number && temp != NULL){ 
    temp = temp->next;
}

if (resnum == temp->_number)
    cout << resnum << " is reserved for " << temp->_name << endl;

if (temp == NULL){
    cout << "Information not found" << endl;
    exit;
}}

Recently I was doing some exercises on Singly Linked List. The above code works if the "resnum" (reservation number) is on the List, but if I enter a number that is not on the list I get an error:

"AirLine Reservation.exe" has stopped working..."

Can someone please help me resolve this error?

Upvotes: 0

Views: 425

Answers (1)

novalain
novalain

Reputation: 2209

The program crashes because of the conditions in the while loop.

You have to check if temp != NULL before you do resnum != temp->_number as the loop testes the conditions in that order and thus tries to access a value of NULL and crashes.

Upvotes: 2

Related Questions