Suppose headA points to [1, 3, 5, 7, 9, 11] and headB points to [2, 4,9, 11]. I want to find the common intersecting elementproblem statement
I am not understanding why a_pointer
and b_pointer
is returning a null list in the end.
I followed this tutorial
Algorithm followed:(as below)
#include<bits/stdc++.h>
struct ListNode {
int val;
ListNode *next;
ListNode() : val(0), next(nullptr) {}
ListNode(int x) : val(x), next(nullptr) {}
ListNode(int x, ListNode *head) { val = x; next = head; }
};
class Solution {
public:
void print(ListNode *head)
{
while(head != nullptr)
{
printf("%d ->", head->val );
head = head->next;
}
printf("\n");
}
ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
print(headA);
print(headB);
ListNode *a_pointer, *b_pointer;
a_pointer = headA;
b_pointer = headB;
while(a_pointer != b_pointer)
{
if(a_pointer == nullptr)
{
a_pointer = headB;
}
else
{
a_pointer = a_pointer->next;
}
if(b_pointer == nullptr)
{
b_pointer = headA;
}
else
{
b_pointer = b_pointer->next;
}
}
print(a_pointer);
print(b_pointer);
return a_pointer;
}
};
int main()
{
Solution s;
ListNode *node1 = new ListNode(1);
node1->next = new ListNode(3);
node1->next->next = new ListNode(5);
node1->next->next->next = new ListNode(7);
node1->next->next->next->next = new ListNode(9);
node1->next->next->next->next->next = new ListNode(11);
ListNode *node2 = new ListNode(2);
node2->next = new ListNode(4);
node2->next->next = new ListNode(9);
node2->next->next->next = new ListNode(11);
ListNode *ret = s.getIntersectionNode(node1,node2);
}
I am not understanding why the assignment a_pointer = headB is changing the original headB pointer.
It is reasonable to not understand why original headB pointer would be changed, because the original headB pointer is not being changed.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.