[LeetCode 160]C++实现相交链表
示例:
输入:intersectVal = 8, listA = [4,1,8,4,5], listB = [5,0,1,8,4,5], skipA = 2, skipB = 3
输出:Reference of the node with value = 8
输入解释:相交节点的值为 8 (注意,如果两个链表相交则不能为 0)。从各自的表头开始算起,链表 A 为 [4,1,8,4,5],链表 B 为 [5,0,1,8,4,5]。在 A 中,相交节点前有 2 个节点;在 B 中,相交节点前有 3 个节点。
来源:力扣(LeetCode 160)
链接:https://leetcode-cn.com/problems/intersection-of-two-linked-lists
方法1、使用STL中set
class Solution {
public:
ListNode* getIntersectionNode(ListNode *headA, ListNode *headB) {
set<ListNode* > s;
while(headA){
s.insert(headA);
headA=headA->next;
}
while(headB){
if(s.find(headB)==s.end()){
s.insert(headB);
headB=headB->next;
}
else{
return headB;
}
}
return NULL;
}
};
方法2、减小长链表至二者长度相等,遍历到相等
class Solution {
public:
int getSize(ListNode* head){
int count=0;
while(head!=NULL){
count++;
head=head->next;
}
return count;
}
ListNode* removeLonger(ListNode* head,int long_len,int short_len){
int length=long_len-short_len;
while(head&&length--){
head=head->next;
}
return head;
}
ListNode* getIntersectionNode(ListNode *headA, ListNode *headB) {
int A_Size=getSize(headA);
int B_Size=getSize(headB);
if(A_Size>B_Size){
headA=removeLonger(headA,A_Size,B_Size);
}
else{
headB=removeLonger(headB,B_Size,A_Size);
}
while(headA!=headB){
headA=headA->next;
headB=headB->next;
}
if(headA!=NULL)
return headA;
else
return NULL;
}
};