-
Notifications
You must be signed in to change notification settings - Fork 539
/
Intersection of Two Linked Lists.cpp
45 lines (45 loc) · 1.08 KB
/
Intersection of Two Linked Lists.cpp
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
38
39
40
41
42
43
44
45
/**
* 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) {
ListNode *curA, *curB;
curA = headA;
curB = headB;
if(curA == NULL || curB == NULL){
return NULL;
}
int length_a = getLength(curA);
int length_b = getLength(curB);
if(length_a > length_b){
for(int i=0; i < length_a-length_b; i++){
curA = curA->next;
}
}
else if(length_a < length_b){
for(int i=0; i < length_b-length_a; i++){
curB = curB->next;
}
}
while(curA != curB){
curA = curA->next;
curB = curB->next;
}
return curA;
}
private:
int getLength(ListNode *head){
int length = 1;
while(head->next != NULL){
head = head->next;
length++;
}
return length;
}
};