大佬的思路很好,是通过两个指针分别遍历相同的距离实现找到第一个相同节点。
遍历两次,第一次用来消除长度差异,第二次找到相同点。
public class Solution {
public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
ListNode p,q;
p = headA;
q = headB;
if(p==null||q==null)return null;
while(p!=q)
{
p=p==null?headB:p.next;
q=q==null?headA:q.next;
}
return q;
}
}
另外一种思路是通过一次遍历,将链表连成环,找环的起点。
class Solution {
public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
if (headA == null || headB == null) {
return null;
}
ListNode last = headB;
while (last.next != null) {
last = last.next;
}
last.next = headB;
ListNode fast = headA;
ListNode slow = headA;
while (fast != null && fast.next != null) {
slow = slow.next;
fast = fast.next.next;
if (slow == fast) {
slow = headA;
while (slow != fast) {
slow = slow.next;
fast = fast.next;
}
last.next = null;
return fast;
}
}
last.next = null;
return null;
}
}