一、哈希集合
判断两个链表是否相交,可以使用哈希集合存储链表节点。
首先遍历链表 headA,并将链表 headA 中的每个节点加入哈希集合中。然后遍历链表 headB,对于遍历到的每个节点,判断该节点是否在哈希集合中:
- 如果当前节点不在哈希集合中,则继续遍历下一个节点;
- 如果当前节点在哈希集合中,则后面的节点都在哈希集合中,即从当前节点开始的所有节点都在两个链表的相交部分,因此在链表headB 中遍历到的第一个在哈希集合中的节点就是两个链表相交的节点,返回该节点。
如果链表 headB 中的所有节点都不在哈希集合中,则两个链表不相交,返回 null。
class Solution {public:ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {unordered_set<ListNode*> visited;ListNode* temp1 = headA;ListNode* temp2 = headB;while(temp1){visited.insert(temp1);temp1 = temp1->next;}while(temp2){if(visited.find(temp2)!=visited.end())return temp2;elsetemp2 = temp2->next;}return NULL;}};
二、双指针
两个链表同时向后移动,如果移动到NULL,则移动至另一链表的头结点,知道相交。
class Solution {public:ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {if(headA==NULL || headB==NULL)return NULL;ListNode* temp1 = headA;ListNode* temp2 = headB;while(temp1!=temp2){if(temp1)temp1 = temp1->next;elsetemp1 = headB;if(temp2)temp2 = temp2->next;elsetemp2 = headA;}return temp1;}};
