I have been trying to solve a leetcode question that shows error in a particular test case.
the question is you are given the heads of two singly linked-lists headA and headB, return the node at which the two lists intersect. If the two linked lists have no intersection at all, return null.
For example, the following two linked lists begin to intersect at node c1
:
enter image description here
The test cases are generated such that there are no cycles anywhere in the entire linked structure.
Note that the linked lists must retain their original structure after the function returns.
Custom Judge:
The inputs to the judge are given as follows (your program is not given these inputs):
-
intersectVal
– The value of the node where the intersection occurs. This is0
if there is no intersected node. -
listA
– The first linked list. -
listB
– The second linked list. -
skipA
– The number of nodes to skip ahead inlistA
(starting from the head) to get to the intersected node. -
skipB
– The number of nodes to skip ahead inlistB
(starting from the head) to get to the intersected node.
The judge will then create the linked structure based on these inputs and pass the two heads, headA
and headB
to your program. If you correctly return the intersected node, then your solution will be accepted.
I wrote the code that solved most of the test cases but it showed error in one test code which is as follows:
intersectVal – 30
listA – [1,3,5,7,9,11,13,15,17,19,21,23,25,27,29,30,31,32]
listB – [30,31,32]
skipA – 15
skipB – 0
Output – No intersection…
Expected – Intersected at ’30’…
I even tried to solve a similar test case which was a custom test code made by me and it was working perfectly:
intersectVal – 5
listA – [1,3,5,7,9]
listB – [5,7,9]
skipA – 2
skipB – 0
output – Intersected at ‘5’
expected – Intersected at ‘5’
Here is my code:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode *getIntersectionNode(ListNode * &headA, ListNode * &headB) {
ListNode* node1 = headA;
ListNode* node2 = headB;
map<ListNode*, bool> visited;
while(node1 != NULL || node2 != NULL){
if (visited[node1] == true){
return node1;
}
else{
visited[node1] = true;
if (node1 != NULL){
node1 = node1 -> next;
}
}
if(visited[node2] == true){
return node2;
}
else{
visited[node2] = true;
if (node2 != NULL){
node2 = node2 -> next;
}
}
}
return NULL;
}
};
I want to know the problem and solution for it.