牛客(36)两个链表的第一个公共结点
// 题目描述 // 输入两个链表,找出它们的第一个公共结点。 public static class ListNode { int val; ListNode next = null; ListNode(int val) { this.val = val; } } public static ListNode FindFirstCommonNode(ListNode pHead1, ListNode pHead2) { if (pHead1 == null||pHead2 == null) { return null; } int count1=0; ListNode p1 = pHead1; while(p1!=null){ count1++; p1 = p1.next; } int count2=0; ListNode p2 = pHead2; while(p2!=null){ count2++; p2 = p2.next; } if (count1>count2){ while (count1>count2){ pHead1 = pHead1.next; count1--; } } if (count1<count2){ while (count1<count2){ pHead2 = pHead2.next; count2--; } } while (pHead1!=pHead2){ pHead2 = pHead2.next; pHead1 = pHead1.next; } return pHead2; }