传送门
nowcoder
leetcode
题目描述
输入两个无环的单向链表,找出它们的第一个公共结点,如果没有公共节点则返回空。
C++ 代码 - nowcoder
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
|
class Solution { public: ListNode* FindFirstCommonNode( ListNode* pHead1, ListNode* pHead2) { if (pHead1 == nullptr || pHead2 == nullptr) return nullptr;
ListNode *p1 = pHead1, *p2 = pHead2; while (p1 != p2) { p1 = (p1 == nullptr ? pHead2 : p1->next); p2 = (p2 == nullptr ? pHead1 : p2->next); }
return p1; } };
|
C++ 代码 - leetcode
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47
|
class Solution { public: ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) { if (headA == nullptr || headB == nullptr) return nullptr;
ListNode *p1 = headA, *p2 = headB; while (p1 != p2) { p1 = (p1 == nullptr ? headB : p1->next); p2 = (p2 == nullptr ? headA : p2->next); }
return p1; } };
class Solution { public: ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) { unordered_set<ListNode*> set;
ListNode* temp = headA; while (temp != nullptr) { set.insert(temp); temp = temp->next; }
temp = headB; while (temp != nullptr) { if (set.count(temp)) return temp; else temp = temp->next; }
return nullptr; } };
|