题解 | #两个链表的第一个公共结点#

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

https://www.nowcoder.com/practice/6ab1d9a29e88450685099d45c9e31e46

哈希:遍历两个链表,将一个链表存进去,用另一个到表中去找

/*
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*> arr;
		while(pHead1)
		{
			arr.insert(pHead1);
			pHead1 = pHead1->next;
		}
		while(pHead2)
		{
			if(arr.count(pHead2)) return pHead2;
			pHead2 = pHead2->next;
		}
		return {};
    }
};

全部评论

相关推荐

点赞 收藏 评论
分享
牛客网
牛客企业服务