-
Notifications
You must be signed in to change notification settings - Fork 0
/
160_get_intersection_node.cc
57 lines (53 loc) · 1.11 KB
/
160_get_intersection_node.cc
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
#include <vector>
#include <algorithm>
#include <string>
#include <map>
#include <set>
#include <iostream>
#include <tuple>
#include <queue>
#include <stack>
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 n1 = 0, n2 = 0;
ListNode *taila = nullptr, *tailb = nullptr;
ListNode *p1 = headA, *p2 = headB;
while (p1) {
++n1;
taila = p1;
p1 = p1->next;
}
while (p2) {
++n2;
tailb = p2;
p2 = p2->next;
}
if (n1 == 0 || n2 == 0 || taila != tailb)
return nullptr;
if (n1 > n2) {
p1 = headA;
p2 = headB;
} else {
p1 = headB;
p2 = headA;
}
for (int i = 0; i < abs(n1 - n2); ++i)
p1 = p1->next;
while (p1 != p2) {
p1 = p1->next;
p2 = p2->next;
}
return p1;
}
};
int main()
{
return 0;
}