1.题目
给你两个单链表的头节点 headA
和 headB
,请你找出并返回两个单链表相交的起始节点。如果两个链表不存在相交节点,返回 null
。
图示两个链表在节点 c1
开始相交:
题目数据 保证 整个链式结构中不存在环。
注意,函数返回结果后,链表必须 保持其原始结构
2.答案
/**
* 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) {
unordered_set <ListNode*> node;
ListNode *temp=headA;
while(temp!=nullptr){
node.insert(temp);
temp=temp->next;
}
temp=headB;
while (temp != nullptr) {
if (node.count(temp)) {
count()
的作用
count()
是集合的方法,用于检查某个元素是否存在于集合中。返回值:
1
:如果元素存在于集合中。
0
:如果元素不存在于集合中。3.
node.count(temp)
的含义
检查
temp
是否存在于集合node
中。如果存在,返回
1
;否则返回0
。
return temp;
}
temp = temp->next;
}
return nullptr;
}
};
我发现hot 都要用哈希表啊?