/* public class ListNode { int val; ListNode next = null; ListNode(int val) { this.val = val; } }*/ public class Solution { // 由于公共部分在链表后面,所以先统计长度, 然后移动长的节点,保证2个节点长度相同,在同时比较。 public ListNode FindFirstCommonNode(ListNode pHead1, ListNode pHead2) { int h1 = 0; int h2 = 0; for (ListNode node = pHead1; node != null; node = node.next) { h1++; } for (ListNode node = pHead2; node != null; node = node.next) { h2++; } ListNode cu2 = pHead2; ListNode cu1 = pHead1; int i = 0; if (h1 < h2) { while (i < h2 - h1) { cu2 = cu2.next; i++; } } int j = 0; if (h1 > h2) { while (j < h1 - h2) { cu1 = cu1.next; j++; } } while (cu1 != null && cu2 != null) { if (cu1.val == cu2.val) { return cu1; } cu1 = cu1.next; cu2 = cu2.next; } return null; } }