Skip to content

Commit f16d766

Browse files
committed
Added to Linked-List
1 parent dd3054b commit f16d766

File tree

1 file changed

+78
-0
lines changed

1 file changed

+78
-0
lines changed
Lines changed: 78 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,78 @@
1+
/*
2+
Src : LeetCode
3+
--------------
4+
5+
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.
6+
For example, the following two linked lists begin to intersect at node c1:
7+
8+
A: a1 --- a2
9+
\
10+
c1 --- c2 --- c3
11+
/
12+
B: b1 --- b2 --- b3
13+
14+
It is guaranteed that there are no cycles anywhere in the entire linked structure.
15+
Note that the linked lists must retain their original structure after the function returns.
16+
17+
Example:
18+
19+
A: 4 --- 1
20+
\
21+
8 --- 4 --- 5
22+
/
23+
B: 5 --- 6 --- 1
24+
25+
Input: intersectVal = 8, listA = [4,1,8,4,5], listB = [5,6,1,8,4,5], skipA = 2, skipB = 3
26+
Output: Intersected at '8'
27+
Explanation: The intersected node's value is 8 (note that this must not be 0 if the two lists intersect).
28+
From the head of A, it reads as [4,1,8,4,5]. From the head of B, it reads as [5,6,1,8,4,5]. There are 2 nodes before the intersected node in A; There are 3 nodes before the intersected node in B.
29+
30+
31+
Constraints:
32+
33+
# The number of nodes of listA is in the m.
34+
# The number of nodes of listB is in the n.
35+
# 0 <= m, n <= 3 * 104
36+
# 1 <= Node.val <= 105
37+
# 0 <= skipA <= m
38+
# 0 <= skipB <= n
39+
# intersectVal is 0 if listA and listB do not intersect.
40+
3 intersectVal == listA[skipA + 1] == listB[skipB + 1] if listA and listB intersect.
41+
42+
43+
Follow up: Could you write a solution that runs in O(n) time and use only O(1) memory?
44+
45+
*/
46+
47+
/**
48+
* Definition for singly-linked list.
49+
* struct ListNode {
50+
* int val;
51+
* ListNode *next;
52+
* ListNode(int x) : val(x), next(NULL) {}
53+
* };
54+
*/
55+
class Solution {
56+
public:
57+
ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
58+
ListNode *p1 = headA;
59+
ListNode *p2 = headB;
60+
61+
if (p1 == NULL || p2 == NULL) return NULL;
62+
63+
while (p1 != NULL && p2 != NULL && p1 != p2) {
64+
p1 = p1->next;
65+
p2 = p2->next;
66+
if (p1 == p2) return p1;
67+
if (p1 == NULL) p1 = headB;
68+
if (p2 == NULL) p2 = headA;
69+
}
70+
71+
return p1;
72+
}
73+
};
74+
75+
76+
//CODE
77+
//Time Complexity = O(n)
78+
//Space Complexity = O(1)

0 commit comments

Comments
 (0)