题解 | #两个链表的第一个公共结点#
两个链表的第一个公共结点
https://www.nowcoder.com/practice/6ab1d9a29e88450685099d45c9e31e46
/* public class ListNode { int val; ListNode next = null; ListNode(int val) { this.val = val; } }*/ public class Solution { public ListNode FindFirstCommonNode(ListNode pHead1, ListNode pHead2) { int count1 = countList(pHead1); int count2 = countList(pHead2); int count = Math.abs(count1-count2); ListNode node1 = count1>=count2?pHead1:pHead2; ListNode node2 = count1>=count2?pHead2:pHead1; for(int i=0;i<count;i++){ node1 = node1.next; } while(node1!=null && node2!=null){ if(node1!=node2){ node1 = node1.next; node2 = node2.next; }else return node1; } return null; } public int countList(ListNode head){ ListNode node = head; int count = 0; while(node!=null){ count++; node = node.next; } return count; } }