Skip to content

Commit 8ca5b9b

Browse files
committed
Add solution for intersection of two linked lists
1 parent 48a8030 commit 8ca5b9b

File tree

1 file changed

+27
-0
lines changed

1 file changed

+27
-0
lines changed

Intersection of Two Linked Lists.js

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,33 @@ Your code should preferably run in O(n) time and use only O(1) memory.
2828
* }
2929
*/
3030

31+
// better solution
32+
33+
/**
34+
* Definition for singly-linked list.
35+
* function ListNode(val) {
36+
* this.val = val;
37+
* this.next = null;
38+
* }
39+
*/
40+
41+
/**
42+
* @param {ListNode} headA
43+
* @param {ListNode} headB
44+
* @return {ListNode}
45+
*/
46+
var getIntersectionNode = function(headA, headB) {
47+
let nodeA = headA;
48+
let nodeB = headB;
49+
50+
while (nodeA !== nodeB) {
51+
nodeA = (nodeA === null) ? headB : nodeA.next;
52+
nodeB = (nodeB === null) ? headA : nodeB.next;
53+
}
54+
55+
return nodeA;
56+
};
57+
3158
/**
3259
* @param {ListNode} headA
3360
* @param {ListNode} headB

0 commit comments

Comments
 (0)