我用C语言编写了一个程序来查找两个链表的交点。但是,当我运行它时,函数“ jumping”的行“ shortest_temp = shortest_temp-> next;”上确实出现错误EXC_BAD_ACCESS(代码= 1,地址= 0x8)。你知道我怎么适应吗?谢谢!
struct Node{
int value;
struct Node *next;
};
int jumping(int diff, struct Node* longest_list, struct Node* shortest_list);
void push(struct Node** head_ref, int new_data){
struct Node* new_node = (struct Node*) malloc(sizeof(struct Node));
new_node->value = new_data;
new_node->next = *head_ref;
*head_ref = new_node;
}
int counter(struct Node* head){
int counter = 0;
struct Node* current = head;
while(current != NULL){
counter++;
current = current->next;
}
return counter;
}
int difference(struct Node* list_one, struct Node* list_two){
int diff;
if(counter(list_one)>counter(list_two)){
diff = counter(list_one) - counter(list_two);
return jumping(diff, list_one, list_two);
}
else{
diff = counter(list_two) - counter(list_one);
return jumping(diff, list_two, list_one);
}
}
int jumping(int diff, struct Node* longest_list, struct Node* shortest_list){
struct Node* longest_temp = longest_list;
struct Node* shortest_temp = shortest_list;
for(int i=0; i < diff ; i++){
longest_temp = longest_temp -> next;
i++;
}
while(longest_list != NULL && shortest_list !=NULL){
longest_temp = longest_temp->next;
shortest_temp = shortest_temp->next;
if(longest_temp == shortest_temp){
return shortest_list->value;
}
}
return -1;
}
int main(int argc, char* argv[]){
struct Node* list_one = NULL;
struct Node* list_two = NULL;
push(&list_one,4);
push(&list_one,5);
push(&list_two,1);
push(&list_two,2);
push(&list_two,3);
push(&list_two,4);
push(&list_two,5);
printf("difference: %d", difference(list_one,list_two));
return 0;
}
谢谢!
答案 0 :(得分:0)
关于:
longest_temp = longest_temp->next;
shortest_temp = shortest_temp->next;
以上更改了指针longest_temp
和shortest_temp
指向的位置。但是,该更改可能使这些指针中的任何一个现在都包含NULL。
然后声明:
return shortest_list->value;
可能正在访问地址0(NULL)的某些偏移量。这会导致段故障事件。
在访问该指针的任何偏移之前,始终检查每个指针是否为NULL。