题解 | #两个链表的第一个公共结点#
两个链表的第一个公共结点
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) { if(pHead1==null||pHead2==null){ return null; } ListNode p1 = pHead1; ListNode p2 = pHead2; while(p2.next!=null){ p2 = p2.next; } p2.next = pHead2; ListNode t1 = pHead1; ListNode t2 = pHead1; while(t1!=null&&t1.next!=null){ t1 = t1.next.next; t2 = t2.next; if(t1==t2){ ListNode target = pHead1; while(t2!=target){ t2 = t2.next; target = target.next; } p2.next = null; return target; } } return null; } }
思路:将其中一个链表的尾节点连接头节点,形成一个环。那么问题就变成了寻找环的入口