两个链表的交点set解决法

求两个链表的交点使用set集合来做

#include 
#include 
using namespace std;
struct ListNode{
    int val;
    ListNode *next;
};
ListNode* getIntersectionNode(ListNode *headA,ListNode *headB){
    set<ListNode*> node_set;
    while(headA){
        node_set.insert(headA);
        headA=headA->next;
    }
    while(headB){
        if(node_set.find(headB)!=node_set.end()){
            return headB;
        }
        headB=headB->next;
    }
    return NULL;
}

int main() {
    ListNode a;
    ListNode b;
    ListNode c;
    ListNode d;
    ListNode e;
    ListNode f;
    a.val=1;
    b.val=2;
    c.val=3;
    d.val=4;
    e.val=5;
    f.val=6;
    a.next=&b;
    b.next=&c;
    c.next=&d;
    d.next=&e;
    e.next=&f;
    f.next=NULL;
    
    ListNode a1;
    ListNode b1;
    ListNode c1;
    a1.val=3;
    b1.val=2;
    c1.val=1;
    a1.next=&b1;
    b1.next=&c1;
    c1.next=&d;
    ListNode* headA=&a;
    ListNode* headB=&a1;
    while(headA){
        cout<<"A:"<<headA->val<<endl;
        cout<<"B:"<<headB->val<<endl;
        headA=headA->next;
        headB=headB->next;
    }
    headA=&a;
    headB=&a1;
    ListNode* result;
    result=getIntersectionNode(headA,headB);
    cout<<result->val<<endl;
    cout<<result->next<<endl;
	return 0;
}

你可能感兴趣的:(C++,数据结构,两个链表求交点se解决t)