题解 | #两个链表的第一个公共结点#
两个链表的第一个公共结点
https://www.nowcoder.com/practice/6ab1d9a29e88450685099d45c9e31e46
import java.util.*; /* public class ListNode { int val; ListNode next = null; ListNode(int val) { this.val = val; } }*/ public class Solution { public ListNode FindFirstCommonNode(ListNode pHead1, ListNode pHead2) { ListNode cur1 = pHead1; ListNode cur2 = pHead2; int list1 = getListLength(cur1); int list2 = getListLength(cur2); int dis = Math.abs(list1 - list2); ListNode longlist = list1 > list2 ? pHead1 : pHead2; ListNode shortlist = list1 > list2 ? pHead2 : pHead1; for(int i = 0; i < dis; i++){ longlist = longlist.next; } while(longlist != shortlist){ longlist = longlist.next; shortlist = shortlist.next; } return shortlist; } private int getListLength(ListNode pHead){ int length = 0; ListNode cur = pHead; while(cur != null){ length++; cur = cur.next; } return length; } }
解题关键
找到长短链表的差距,让长链表走完这个距离