-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path160_getIntersectionNode.cpp
More file actions
37 lines (37 loc) · 895 Bytes
/
Copy path160_getIntersectionNode.cpp
File metadata and controls
37 lines (37 loc) · 895 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
int lenA = 0,lenB = 0;
ListNode *p = headA,*q = headB;
while(p!=NULL||q!=NULL){
if(p!=NULL){
lenA++;
p = p->next;
}
if(q!=NULL){
lenB++;
q = q->next;
}
}
if(lenA>lenB){
for(int i = 0;i<lenA-lenB;i++)
headA = headA->next;
}else{
for(int i = 0;i<lenB-lenA;i++)
headB = headB->next;
}
while(headA!=headB){
headA = headA->next;
headB = headB->next;
}
return headA;
}
};