相交链表
[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;
}
};

浙公网安备 33010602011771号