-
-
Notifications
You must be signed in to change notification settings - Fork 300
/
160.cpp
112 lines (103 loc) · 2.69 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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
__________________________________________________________________________________________________
36ms
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
static const auto s = []() {
std::ios::sync_with_stdio(false);
std::cin.tie(nullptr);
return nullptr;
}();
class Solution {
public:
ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
if(headA == nullptr || headB == nullptr)
return NULL;
int lenA = listLen(headA);
int lenB = listLen(headB);
if(lenA >= lenB){
int dis = lenA - lenB;
while(dis> 0){
headA = headA->next;
dis--;
}
}
else{
int dis = lenB - lenA;
while(dis > 0){
headB = headB->next;
dis--;
}
}
while(headA!=nullptr && headB!= nullptr){
if(headA == headB)
return headA;
headA = headA->next;
headB = headB->next;
}
return NULL;
}
int listLen(ListNode *head){
if(head == nullptr)
return 0;
int len = 0;
while(head!=nullptr){
len++;
head = head->next;
}
return len;
}
};
__________________________________________________________________________________________________
16508 kb
/**
* 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 = getListLength(headA);
int lenB = getListLength(headB);
if(lenA > lenB){
headA = goForward(lenA, lenB, headA);
}
else{
headB = goForward(lenB, lenA, headB);
}
while(headA && headB){
if(headA == headB){
return headA;
}
headA = headA->next;
headB = headB->next;
}
return NULL;
}
int getListLength(ListNode *head){
int len = 0;
while(head){
head = head->next;
len++;
}
return len;
}
ListNode *goForward(int long_len, int short_len, ListNode *head){
int delta = long_len - short_len;
while(head && delta){
head = head->next;
delta--;
}
return head;
}
};
__________________________________________________________________________________________________