相交链表

[https://leetcode-cn.com/problems/intersection-of-two-linked-lists/](LeetCode 160)

//方法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;

}

};

posted @ 2020-11-04 21:54  Colin_Code  阅读(59)  评论(0)    收藏  举报