使用LinkedList检查值

时间:2015-06-16 19:55:59

标签: c++ singly-linked-list

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;
}}

最近我在Singly Linked List上做了一些练习。以上代码适用于&#34; resnum&#34; (预订号码)在列表中,但如果我输入一个不在列表中的号码,我会收到错误:

  

&#34; AirLine Reservation.exe&#34;已停止工作......&#34;

有人可以帮我解决这个错误吗?

1 个答案:

答案 0 :(得分:2)

由于while循环中的条件,程序崩溃。

您必须先检查temp != NULL 之前是否<{strong>> resnum != temp->_number,因为循环会按此顺序测试条件,因此会尝试访问NULL值并崩溃。< / p>