-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathIntersection_of_Two_Linked_Lists.cpp
More file actions
67 lines (67 loc) · 1.42 KB
/
Intersection_of_Two_Linked_Lists.cpp
File metadata and controls
67 lines (67 loc) · 1.42 KB
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
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
/*Intersection of Two Linked Lists,找两个链表的交点 用Map空间复杂度高*/
ListNode *getIntersectionNode(ListNode *headA, ListNode *headB)
{
unordered_map<ListNode*, int> m_map;
ListNode *head_a = headA, *head_b = headB;
while (head_a)
{
m_map[head_a] = 1;
head_a = head_a->next;
}
while (head_b)
{
auto res = m_map.find(head_b);
if (res != m_map.end())
return head_b;
else
m_map[head_b] = 1;
head_b = head_b->next;
}
return nullptr;
}
/*方法2,时间复杂度O(N),空间复杂度O(1)*/
ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
ListNode *head_a = headA, *head_b = headB;
int lengthA = 0, lengthB = 0;
while (head_a)
{
lengthA++;
head_a = head_a->next;
}
while (head_b)
{
lengthB++;
head_b = head_b->next;
}
int diff = abs(lengthA - lengthB); //计算两个链表的长短之差
int flag = lengthA < lengthB ? 1 : 0;
while (diff--)
{
if (flag)
headB = headB->next;
else
headA = headA->next;
}
while (headA && headB)
{
if (headA == headB)
return headA;
else
{
headA = headA->next;
headB = headB->next;
}
}
return nullptr;
}
};