Skip to content

Commit fcbe62a

Browse files
authored
Created intersection-of-two-linked-lists.cpp
intersection-of-two-linked-lists.cpp
1 parent 727ad08 commit fcbe62a

File tree

1 file changed

+26
-0
lines changed

1 file changed

+26
-0
lines changed
Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
// Given the heads of two singly linked-lists headA and headB, return the node at which the two lists intersect.
2+
// If the two linked lists have no intersection at all, return null.
3+
4+
// Time: O(m + n)
5+
// Space: O(1)
6+
7+
/**
8+
* Definition for singly-linked list.
9+
* struct ListNode {
10+
* int val;
11+
* ListNode *next;
12+
* ListNode(int x) : val(x), next(NULL) {}
13+
* };
14+
*/
15+
16+
class Solution {
17+
public:
18+
ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
19+
ListNode *curA = headA, *curB = headB;
20+
while (curA != curB) {
21+
curA = curA ? curA->next : headB;
22+
curB = curB ? curB->next : headA;
23+
}
24+
return curA;
25+
}
26+
};

0 commit comments

Comments
 (0)