2017-05-08 125 views
-1

我想要做的是检查值之后的节点是否是特定的数字,如果是,则删除先前节点。 类似于:C++删除单个链接列表中的另一个节点

1,2,3,4,5,4 如果下一个节点号为4,则删除此节点。 1,2,3,4,5,4 - > 1,2,4,4

node* temp = head; 
while (head != NULL) { 
    if (head->next->number == 4) { 
     delete temp; 
    } 
    head = head->next; 
} 

在这一刻如编译器崩溃挣扎。

+1

您需要包括你得到什么错误。 – Carcigenicate

+0

进程返回255 @CodeBlocks。 – Brock

+1

就像一个参考,你是编译器可能会崩溃,因为你检查'head!= NULL',但是然后你调用'head-> next-> number'。所以'head'可能不是NULL,但是你不能保证'head-> next!= NULL',除非你明确检查。 – LeoVannini

回答

1

你提前之前,您删除头:

node *temp = NULL; 
while (head->next != NULL) { 
    if (head->next->number == 4) { 
     temp = head; 
    } 
    if (temp == NULL){ 
     head = head->next; 
    } 
    else{ 
     head = head->next->next; 
     delete temp; 
     temp= NULL: 
    } 
}