C语言链表反转代码段错误分析及解决方案
#include <stdio.h> #include <stdlib.h> typedef struct Linklist{ int data; struct Linklist* next; }LNode; int num; LNode creatLinklist(){ LNode head=(LNode)malloc(sizeof( LNode)); return head; } LNode addNode(LNode *preNode,int currentData){ LNode currentNode=(LNode)malloc(sizeof( LNode)); currentNode->data=currentData; preNode->next=currentNode; return currentNode; } void initLinklist(LNode *headNode){ scanf('%d',&num); int tmpValue; for(int i=0;i<num;i++){ scanf('%d',&tmpValue); printf('%d ',tmpValue); headNode=addNode(headNode,tmpValue); } } void outPrint(LNode *headNode){ LNode *releaseNode; headNode=headNode->next; while(headNode!=NULL){ printf('%d',headNode->data); releaseNode=headNode; headNode=headNode->next; free(releaseNode); if(headNode!=NULL) printf(' '); } }
void reverse(LNode *head){ LNode *nextOne,*current,*pre; pre=head->next; current=head->next->next; if(current != NULL){ nextOne=current->next; } else{ nextOne = NULL; } while(current!=NULL){ current->next=pre; pre=current; current=nextOne; if(nextOne != NULL){ nextOne=nextOne->next; } } } int main() { int T; scanf('%d ',&T); LNode *head=creatLinklist(); initLinklist(head); // outPrint(head); // printf(' '); reverse(head); outPrint(head); printf(' '); return 0; } 这段代码会导致段错误的原因是在reverse函数中,当current指针指向最后一个节点时,nextOne指针为NULL,而在下一次循环中,current->next会出现空指针解引用的错误。
解决方法是在while循环中添加一个判断条件,当nextOne为NULL时,跳出循环,即可避免空指针解引用的错误。
修改后的代码如下:
void reverse(LNode *head){
LNode *nextOne,*current,*pre;
pre=head->next;
current=head->next->next;
if(current != NULL){
nextOne=current->next;
}
else{
nextOne = NULL;
}
while(current!=NULL){
current->next=pre;
pre=current;
current=nextOne;
if(nextOne != NULL){
nextOne=nextOne->next;
}
}
}
另外,在主函数中也需要调用outPrint函数来输出反转后的链表。
修改后的主函数如下:
int main() {
int T;
scanf('%d
',&T);
LNode *head=creatLinklist();
initLinklist(head);
reverse(head);
outPrint(head);
printf('
');
return 0;
}
原文地址: https://www.cveoy.top/t/topic/paAA 著作权归作者所有。请勿转载和采集!