[剑指 offer] JT36---The first common node of two linked lists (what's the difference between finding the same value with an array?)

Sword Finger Offer Question 36

The topic is as follows

Insert picture description here

Idea and code

I saw that there is a way to calculate the length of two linked lists. I didn't understand it. I just saved one in the map and checked the other. I was superficial. . . Directly!

/*
struct ListNode {
	int val;
	struct ListNode *next;
	ListNode(int x) :
			val(x), next(NULL) {
	}
};*/
class Solution {
    
    
public:
    ListNode* FindFirstCommonNode( ListNode* pHead1, ListNode* pHead2) {
    
    
        ListNode* cur=pHead1;
        map<int,bool> m;
        for(;cur!=NULL;cur=cur->next){
    
    
            m[cur->val]=true;
        }
        for(cur=pHead2;cur!=NULL;cur=cur->next){
    
    
            if(m.find(cur->val)!=m.end()){
    
    
                return cur;
            }
        }
        return NULL;
    }
};

Insert picture description here

Guess you like

Origin blog.csdn.net/qq_42136832/article/details/114939205