问题
I am learning DSA , Linked List , new to C++. My linked list is of exception.
Error Info:
It is much longer than it should be.
Here is my code:
define struct ListNode
// Definition for singly-linked list.
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
get Intersection of Two Linked Lists
ListNode * Solution_three :: getIntersectionNode(ListNode *headA, ListNode *headB) {
ListNode * p_one = headA;
ListNode * p_two = headB;
if (p_one == NULL || p_two == NULL) {
return NULL;
}
while (p_one != NULL && p_two != NULL && p_one != p_two) {
p_one = p_one -> next;
p_two = p_two -> next;
if( p_one == p_two ){
return p_one;
}
if (p_one == NULL) {
p_one = headB;
}
if (p_two == NULL) {
p_two = headA;
}
}
return p_one;
}
construct samples and call Intersection of Two Linked Lists
void Solution_three :: test_Intersection(){
ListNode *node_one = new ListNode(1);
ListNode *two = new ListNode(3);
ListNode *three = new ListNode(5);
ListNode *four = new ListNode(7);
ListNode *five = new ListNode(9);
ListNode *six = new ListNode(11);
node_one->next = two;
two->next = three;
three->next = four;
four->next = five;
five->next = six;
ListNode *node_a_one = new ListNode(2);
ListNode *a_two = new ListNode(5);
ListNode *a_three = new ListNode(9);
ListNode *a_four = new ListNode(19);
node_a_one->next = a_two;
a_two->next = a_three;
a_three->next = a_four;
ListNode node_r = *getIntersectionNode(node_one, node_a_one);
printf("%d", node_r.val);
cout<<"\n"<<node_r.val<<endl;
}
By take a break point, I see the linked list is much longer.
I don't know how to take it out.
回答1:
How could p_one != p_two
be true.
Should overload the operator !=
, to compare the value of the node.
来源:https://stackoverflow.com/questions/51851874/c-node-assign-error-thread-1-exc-bad-access-code-1-address-0x0