Wins the offer - 55 two first common node of the list

Title Description

Two input lists, find their first common node.
Solution:
  each traverse two lists to the end of the chain, and calculates its length, the same as if the last node, the common node is present
  Then let the head pointer to move a long chain length difference between the nodes and pointers move together two lists, the first one and the same node occurs is a common node
  
  
 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         the while (! P2-> Next = nullptr a)
 13 is          {
 14              P2 = P2-> Next;
 15              ++ L2 of;
 16          }
 . 17          IF (P1 = P2!) return nullptr a; // the last node is not the same, there is no intersection point 
18 is          P1 = pHead1;
 . 19          P2 = pHead2;
 20 is          IF (Ll> = L2 of)
 21 is              for ( int I = 0 ; I <Ll - L2 of; I ++) P1 = P1-> Next;
 22 is          the else 
23 is              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 };

 

Guess you like

Origin www.cnblogs.com/zzw1024/p/11706123.html