-
Notifications
You must be signed in to change notification settings - Fork 62
/
intersection_two_lists.cpp
46 lines (40 loc) · 1.02 KB
/
intersection_two_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
// 相交链表
#include "iostream"
#include "set"
using namespace std;
struct ListNode {
int val;
ListNode *next;
ListNode() : val(0), next(nullptr) {}
ListNode(int x) : val(x), next(nullptr) {}
ListNode(int x, ListNode *next) : val(x), next(next) {}
};
class Solution {
public:
// 使用一个集合
ListNode *getIntersectionNode1(ListNode *headA, ListNode *headB) {
set<ListNode*> s;
while (headA) {
s.insert(headA);
headA = headA->next;
}
while (headB) {
auto it = s.find(headB);
if (it != s.end()) {
return headB;
}
headB = headB->next;
}
return nullptr;
}
// 双指针法
ListNode *getIntersectionNode2(ListNode *headA, ListNode *headB) {
ListNode* p = headA;
ListNode* q = headB;
while (p != q) {
p = p == nullptr ? headB : p->next;
q = q == nullptr ? headA : q->next;
}
return p;
}
};