题目描述
输入两个链表,找出它们的第一个公共结点。
题解:
分别遍历两个链表到链尾,并计算其长度,若最后一个节点相同,则存在公共节点
分别遍历两个链表到链尾,并计算其长度,若最后一个节点相同,则存在公共节点
然后让长链表指针从头先移动长度差个节点,然后两个链表指针一起移动,第一个出现的 相同节点就是公共节点
1 class Solution { 2 public: 3 ListNode* FindFirstCommonNode(ListNode* pHead1, ListNode* pHead2) { 4 if (pHead1 == nullptr || pHead2 == nullptr)return nullptr; 5 int L1 = 1, L2 = 1; 6 ListNode *p1 = pHead1, *p2 = pHead2; 7 while (p1->next != nullptr) 8 { 9 p1 = p1->next; 10 ++L1; 11 } 12 while (p2->next != nullptr) 13 { 14 p2 = p2->next; 15 ++L2; 16 } 17 if (p1 != p2)return nullptr;//最后一个节点不相同,则没有相交点 18 p1 = pHead1; 19 p2 = pHead2; 20 if (L1 >= L2) 21 for (int i = 0; i < L1 - L2; ++i)p1 = p1->next; 22 else 23 for (int i = 0; i < L2 - L1; ++i)p2 = p2->next; 24 while (p1 != p2) 25 { 26 p1 = p1->next; 27 p2 = p2->next; 28 } 29 return p1; 30 } 31 };