LeetCode - 160. 相交链表
题目描述
编写一个程序,找到两个单链表相交的起始节点。
如下面的两个链表:
在节点 c1 开始相交。
解题思路
让两个链表从同距离末尾同等距离的位置开始遍历。这个位置只能是较短链表的头结点位置。
class Solutio_160 {
public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
if (headA ==null || headB == null)
return null;
ListNode a = headA,b = headB;
while (a != b){
a = a == null ? headB : a.next;
b = b == null ? headA : b.next;
}
return a;
}
}