-
Notifications
You must be signed in to change notification settings - Fork 1
/
160.cpp
57 lines (45 loc) · 1.28 KB
/
160.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
// 160. Intersection of Two Linked Lists - https://leetcode.com/problems/intersection-of-two-linked-lists
#include "bits/stdc++.h"
using namespace std;
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(nullptr) {}
};
class Solution {
public:
ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
if (headA == nullptr || headB == nullptr) { return nullptr; }
int lengthA = 0, lengthB = 0;
ListNode* curA = headA;
ListNode* curB = headB;
while(curA->next != nullptr) {
curA = curA->next;
++lengthA;
}
while(curB->next != nullptr) {
curB = curB->next;
++lengthB;
}
if (lengthA > lengthB) {
while (lengthA > lengthB) {
headA = headA->next;
--lengthA;
}
} else if (lengthB > lengthA) {
while (lengthB > lengthA) {
headB = headB->next;
--lengthB;
}
}
while (headA != headB) {
headA = headA->next;
headB = headB->next;
}
return headA;
}
};
int main() {
ios::sync_with_stdio(false);
return 0;
}