0
点赞
收藏
分享

微信扫一扫

BM10 两个链表的第一个公共结点

90哦吼 2022-02-26 阅读 51

使用unordered_set暂存元素

/*
struct ListNode {
	int val;
	struct ListNode *next;
	ListNode(int x) :
			val(x), next(NULL) {
	}
};*/
class Solution {
public:
    ListNode* FindFirstCommonNode( ListNode* pHead1, ListNode* pHead2) {
        unordered_set<ListNode*> st;
        
        while(pHead1){
            if(st.find(pHead1)==st.end()){
                st.insert(pHead1);
                pHead1=pHead1->next;
            }
        }
        while(pHead2){
            if(st.find(pHead2)==st.end()){
                st.insert(pHead1);
                pHead2=pHead2->next;
            }
            else{
                return pHead2;
            }
        }
        return nullptr;
        
        
        
    }
};

走两遍重合的路

/*
struct ListNode {
	int val;
	struct ListNode *next;
	ListNode(int x) :
			val(x), next(NULL) {
	}
};*/
class Solution {
public:
    ListNode* FindFirstCommonNode( ListNode* pHead1, ListNode* pHead2) {
        ListNode *l1=pHead1;
        ListNode *l2=pHead2;
        while(l1!=l2){
            l1=l1?l1->next:pHead2;
            l2=l2?l2->next:pHead1;
        }
        return l1;
    }
};

这是牛客官方的答案,重点在走完自己的路之后走别人的路,若没有重合部分的话,都走完后两个节点都会为nullptr。

举报

相关推荐

0 条评论