C中链表删除while循环中&&运算符的异常特性
Unusual characteristics of && operator in while loop in linked list deletion in C
我一直在玩链表,并且了解了带有 AND 运算符的 While 循环的一些不寻常的特性(我猜是这样)。
这是什么:
这是我的删除function.I正在搜索要删除的密钥。
void delet(Mynode** head,int value) {
printf(" deleting... %d\n",value);
Mynode *temp = *head,*prev;
if(temp->val == value) {
*head = (*head)->next;
free(temp);
return;
} else {
while( temp->val != value && temp != NULL) {
prev = temp;
temp=temp->next;
}
}
if(temp == NULL) {
printf("..and %d is not in the list\n",value );
} else{
prev->next = temp->next;
}
}
在 while 循环中,我一直在检查这样的条件。
并且仅针对列表中的值正常工作。
如果要删除的值不在列表中,则会抛出分段错误。
while( temp->val != value && temp != NULL) {
prev = temp;
temp=temp->next;
}
但有趣的是,如果我在 while 循环中交换条件,它可以正常工作而不会出现任何错误。即:
while( temp != NULL && temp->val != value)
我想在 while 循环中交换条件应该不会影响输出。
任何人都可以告诉我这是为什么还是我总是出错。
感谢您的宝贵时间。
条件
temp->val != value && temp != NULL
要求 temp
不为空,temp->val
才能工作。正在测试的第一位。如果 temp
为空,它将崩溃。
因此先判断temp
是否不为null,再查看temp
指向的内容。
即
temp != NULL && temp->val != value
ps: && 是一个短路运算符,一旦它知道答案就会ps求值
我一直在玩链表,并且了解了带有 AND 运算符的 While 循环的一些不寻常的特性(我猜是这样)。
这是什么:
这是我的删除function.I正在搜索要删除的密钥。
void delet(Mynode** head,int value) {
printf(" deleting... %d\n",value);
Mynode *temp = *head,*prev;
if(temp->val == value) {
*head = (*head)->next;
free(temp);
return;
} else {
while( temp->val != value && temp != NULL) {
prev = temp;
temp=temp->next;
}
}
if(temp == NULL) {
printf("..and %d is not in the list\n",value );
} else{
prev->next = temp->next;
}
}
在 while 循环中,我一直在检查这样的条件。 并且仅针对列表中的值正常工作。
如果要删除的值不在列表中,则会抛出分段错误。
while( temp->val != value && temp != NULL) {
prev = temp;
temp=temp->next;
}
但有趣的是,如果我在 while 循环中交换条件,它可以正常工作而不会出现任何错误。即:
while( temp != NULL && temp->val != value)
我想在 while 循环中交换条件应该不会影响输出。
任何人都可以告诉我这是为什么还是我总是出错。
感谢您的宝贵时间。
条件
temp->val != value && temp != NULL
要求 temp
不为空,temp->val
才能工作。正在测试的第一位。如果 temp
为空,它将崩溃。
因此先判断temp
是否不为null,再查看temp
指向的内容。
即
temp != NULL && temp->val != value
ps: && 是一个短路运算符,一旦它知道答案就会ps求值