Skip to content

Commit 0cac5bf

Browse files
author
ZQKC
committed
Problem 160
1 parent 672e756 commit 0cac5bf

File tree

1 file changed

+39
-0
lines changed

1 file changed

+39
-0
lines changed
+39
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
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+
if (headA == NULL || headB == NULL)
13+
return NULL;
14+
15+
ListNode *pA = headA;
16+
while (pA->next != NULL)
17+
pA = pA ->next;
18+
pA -> next = headA;
19+
20+
ListNode *pB_s1 = headB, *pB_s2 = headB;
21+
while (1){
22+
pB_s1 = pB_s1->next != NULL ? pB_s1->next: NULL;
23+
pB_s2 = pB_s2->next != NULL && pB_s2->next->next != NULL ? pB_s2->next->next: NULL;
24+
if (pB_s1 == NULL || pB_s2 == NULL) {
25+
pA -> next = NULL;
26+
return NULL;
27+
}
28+
if (pB_s1 == pB_s2)
29+
break;
30+
}
31+
ListNode *pB = headB;
32+
while (pB != pB_s1){
33+
pB = pB->next;
34+
pB_s1 = pB_s1->next;
35+
}
36+
pA -> next = NULL;
37+
return pB_s1;
38+
}
39+
};

0 commit comments

Comments
 (0)