/* public class ListNode { int val; ListNode next = null; ListNode(int val) { this.val = val; } }*/ public class Solution { public ListNode FindFirstCommonNode(ListNode pHead1, ListNode pHead2) { //任意一条链表为空,就不会有公共节点 if (pHead1 == null || pHead2 == null) { return null; } int c1 = 0; int c2 = 0; ListNode temp1 = pHead1; ListNode temp2 = pHead2; //公共部分等长,所以先保证从两链表等长的地方开始 while (temp1 != null) { c1++; temp1 = temp1.next; } while (temp2 != null) { c2++; temp2 = temp2.next; } int diff = 0; if (c1 >= c2) { diff = c1 - c2; while (diff-->0) { pHead1 = pHead1.next; } } else { diff = c2 - c1; while (diff-->0) { pHead2 = pHead2.next; } } //找公共节点 while (pHead1 != null && pHead2 != null) { if (pHead1 == pHead2) { return pHead1; } pHead1 = pHead1.next; pHead2 = pHead2.next; } return null; } }