两个链表的长度如果相等的话,从头节点开始走,两个指针相等的时候就找到了第一个公共节点。
如果两个链表的长度不相等,假设 比 多 个结点,那就从 的第 个结点开始走, 从头结点开始走,,两个指针相等的时候就找到了第一个公共节点。
然后问题就转化为了如何知道哪个链表的长度更长一点,比长度短的链表多了几个结点。解决这个问题的话,我们只需要先设置两个指针,分别指向两个链表的头节点,然后当一个指针指向空了以后开始计数,看另一个指针走多少步才会指向空。
c++
class Solution { public: ListNode* FindFirstCommonNode( ListNode* pHead1, ListNode* pHead2) { ListNode* L1 = pHead1; ListNode* L2 = pHead2; int l1 = 0,l2 = 0; while(L1 !=NULL || L2!= NULL) { if(L1!=NULL){L1 = L1->next;} else{ l2++; } if(L2 != NULL){L2 = L2->next;} else{ l1++; } } L1 = pHead1; L2 = pHead2; while(l1!=0) { L1 = L1->next; l1--; } while(l2!=0) { L2 = L2->next; l2--; } while(L1!=L2) { L1 = L1->next; L2 = L2->next; } return L1; } };
java
public class Solution { public ListNode FindFirstCommonNode(ListNode pHead1, ListNode pHead2) { ListNode L1 = pHead1; ListNode L2 = pHead2; int l1 = 0,l2 = 0; while(L1 != null || L2!= null) { if(L1!= null){L1 = L1.next;} else{ l2++; } if(L2 != null){L2 = L2.next;} else{ l1++; } } L1 = pHead1; L2 = pHead2; while(l1!=0) { L1 = L1.next; l1--; } while(l2!=0) { L2 = L2.next; l2--; } while(L1!=L2) { L1 = L1.next; L2 = L2.next; } return L1; } }
python
class Solution: def FindFirstCommonNode(self , pHead1 , pHead2 ): # write code here L1 = pHead1 L2 = pHead2 l1 = 0 l2 = 0 while L1 != None or L2!= None: if L1!= None: L1 = L1.next else: l2 = l2+1 if L2 != None: L2 = L2.next else: l1 = l1+1 L1 = pHead1 L2 = pHead2 while l1!=0: L1 = L1.next l1 = l1-1 while l2!=0: L2 = L2.next l2 = l2-1 while L1!=L2: L1 = L1.next L2 = L2.next return L1