题解 | #两个链表的第一个公共结点#
两个链表的第一个公共结点
https://www.nowcoder.com/practice/6ab1d9a29e88450685099d45c9e31e46
public class Solution { //计算链表长度的函数 fast-template public int ListLenth(ListNode pHead){ ListNode p = pHead; int n = 0; while(p != null){ n++; p = p.next; } return n; } public ListNode FindFirstCommonNode(ListNode pHead1, ListNode pHead2) { int p1 = ListLenth(pHead1); int p2 = ListLenth(pHead2); //当链表1更长时,链表1指针先走p1-p2步 if(p1 >= p2){ int n = p1 - p2; for(int i = 0; i < n; i++){ pHead1 = pHead1.next; } //两个链表同时移动,直到有公共结点时停下 while((pHead1 != null) && (pHead2 != null) && (pHead1 != pHead2)){ pHead1 = pHead1.next; pHead2 = pHead2.next; } } //反之,则链表2先行p2-p1步 else{ int n = p2 - p1; for(int i = 0; i < n; i++){ pHead2 = pHead2.next; } //两个链表同时移动,直到有公共结点时停下 while((pHead1 != null) && (pHead2 != null) && (pHead1 != pHead2)){ pHead1 = pHead1.next; pHead2 = pHead2.next; } } return pHead1; } }