c++ - 赋值只在循环外有效
问题描述
我正在学习 CPP(第一语言),并且正在尝试反转链表。此代码不起作用
node* reverse(node** head){
node* previous=NULL;
node* current=*head;
node* nextptr=current->next;
while(current!=NULL){
current->next=previous;
previous=current;
current=nextptr;
nextptr=nextptr->next;
}
return previous;
}
这个正在工作
node* reverse(node** head){
node* previous=NULL;
node* current=*head;
node* nextptr;
while(current!=NULL){
nextptr=current->next;
current->next=previous;
previous=current;
current=nextptr;
}
return previous;
}
为什么第二个代码片段有效,而第一个无效?
解决方案
为什么第二个代码片段有效,而第一个无效?
第一个片段在取消引用潜在的空指针之前不检查。因为您使用空指针来指示列表的结尾,所以它总是取消引用空指针,因此具有未定义的行为。
第二个片段永远不会取消引用它尚未验证为非空的指针。
推荐阅读
- amazon-web-services - 如何将 AWS Cognito 用户池中的 IP 地址列入白名单
- python - 没有路线匹配给定的查询
- vscode-settings - VS Code 格式化程序对 HTML 的工作很奇怪
- machine-learning - 如何从 Open Images Dataset V6 中获取注释数据?
- javascript - 向 typescript .d.ts 文件添加描述
- react-native - 笔记本下一页打开动画
- android - 设备:摩托罗拉 Moto Z2 Play 未出现在 Firebase Crashlytics 中
- javascript - JWT 授权标头返回未定义
- safari - safari 14.1.2 - 无法使用 printjs 打印 pdf
- mysql - 我可以使用 data.sql 的 spring 配置文件来根据环境加载不同的数据吗?