-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathIntersection of Two Linked Lists.cpp
69 lines (52 loc) · 1.18 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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
#include<iostream>
using namespace std;
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
class Solution {
public:
ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
int sizeA = ListSize(headA);
int sizeB = ListSize(headB);
if(headA == NULL || headB == NULL)
return NULL;
int diff = sizeA - sizeB;
ListNode * large = headA;
ListNode * small = headB;
if(sizeA < sizeB){
diff = -diff;
large = headB;
small = headA;
}
cout << sizeA << " " << sizeB << " " << diff << endl;
while((diff--) > 0){
large = large->next;
}
cout << large->val << " " << small->val << endl;
while(large->val != small->val){
large = large -> next;
small = small -> next;
if(large == NULL)
break;
}
return large;
}
int ListSize(ListNode *head){
int size = 0;
while(head){
size++;
head = head -> next;
}
return size;
}
};
int main(){
ListNode* list1 = new ListNode(1);
list1->next = new ListNode(3);
list1->next->next = new ListNode(5);
ListNode* list2 = new ListNode(2);
Solution s;
s.getIntersectionNode(list1,list2);
}