首先想到的是vector< int >存储节点值然后比较,或者弄两次前插从尾部读取公共部分,但是太麻烦了,而且比较的貌似是内存地址,不是值,如下图这组数据:
参考了力扣官方题解:
两个链表的第一个公共节点
1.双指针
/**
* 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*curA=headA;
ListNode*curB=headB;
while(curA!=curB){
curA=curA==NULL?headA:curA->next;
curB=curB==NULL?headB:curB->next;
}
return curA;
}
};
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*> tmp;
ListNode* curA=headA;
ListNode* curB=headB;
while(curA){
tmp.insert(curA);
curA=curA->next;
}
while(curB){
if(tmp.count(curB)){ //if(tmp.find(curB)!=tmp.end()
return curB;
}
curB=curB->next;
}
return NULL;
}
};