Skip to content

Commit a1b3116

Browse files
Create Intersection_LL.cpp
1 parent d85da96 commit a1b3116

File tree

1 file changed

+32
-0
lines changed

1 file changed

+32
-0
lines changed

Linked List/Intersection_LL.cpp

+32
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
/**
2+
* Definition for singly-linked list.
3+
* struct ListNode {
4+
* int val;
5+
* ListNode *next;
6+
* ListNode(int x) : val(x), next(NULL) {}
7+
* };
8+
*/
9+
class Solution {
10+
public:
11+
ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
12+
ListNode *pA = headA;
13+
ListNode *pB = headB;
14+
15+
// Traverse both linked lists until they meet or reach the end (NULL)
16+
while (pA != pB) {
17+
// Move pointers to the next node
18+
pA = (pA != nullptr) ? pA->next : headB;
19+
pB = (pB != nullptr) ? pB->next : headA;
20+
}
21+
22+
// Return the intersection node (or NULL if no intersection)
23+
return pA;
24+
}
25+
};
26+
27+
/*
28+
Explanation:
29+
The provided code implements the solution to find the intersection point of two singly-linked lists headA and headB. The getIntersectionNode function takes two ListNode pointers as parameters and returns the intersection node if one exists, or NULL if there is no intersection.
30+
31+
The approach used here is based on the concept of "runner pointers." The pointers pA and pB start from the heads of the two linked lists and traverse through the lists. When a pointer reaches the end of its list, it is redirected to the head of the other list. This ensures that the pointers will meet at the intersection point if it exists, or they will both reach the end of the lists (NULL) simultaneously if there is no intersection.
32+
*/

0 commit comments

Comments
 (0)