🔗 leetcode.cn/problems/in…
题目
- 返回两个链表相交的第一个节点,如果不相交返回 nullptr
思路
- hashset 比较直观
- 双指针比较妙,遍历完自己的指针后,遍历另一个链表的指针,空间复杂度优
代码
/**
* 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*> s
ListNode* head = headA
while (head) {
s.insert(head)
head = head->next
}
head = headB
while (head) {
if (s.count(head) > 0) return head
head = head->next
}
return nullptr
}
}