题目描述
给你两个单链表的头节点 headA 和 headB ,请你找出并返回两个单链表相交的起始节点。如果两个链表没有交点,返回 null 。图示两个链表在节点 c1 开始相交:

链接:https://leetcode-cn.com/problems/intersection-of-two-linked-lists
解题思路
采用哈希表记录
/*** 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*> record;while (headA) {record.insert(headA);headA = headA->next;}while (headB) {if (record.count(headB))return headB;headB = headB->next;}return NULL;}};
假设链表a长度为:l1+l,链表b长度为l2+l,那么链表a的指针走完后指向链表b,链表b的指针走完后指向链表a,最终相遇的时候为为相交点:l1+l+l2 = l2+l+l1
/*** 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) {ListNode *pA, *pB;pA = headA;pB = headB;while (pA != pB) {pA = pA == NULL ? headB : pA->next;pB = pB == NULL ? headA : pB->next;}return pA;}};
