编写一个程序,找到两个单链表相交的起始节点。LeetCode160题,剑指offer上的题
public static ListNode getIntersectionNode(ListNode headA, ListNode headB) {
if (headA == null || headB == null)
return null;
ListNode p = headA, q = headB;
int count = 0;
//先让两个链表分别跑一遍,如果尾节点相同,说明该链表是一个相交链表
for (p = headA; p.next != null; p = p.next, count++) ;
for (q = headB; q.next != null; q = q.next, count--) ;
if (q.val != p.val)
return null;
if (count > 0) {
p = headA;
q = headB;
} else {
p = headB;
q = headA;
count = -count;
}
//长的链表先开始跑count个位置
for (; count != 0; count--, p = p.next) ;
//两个链表一起跑,如过某个节点这;两个链表相同,说明这个节点是交叉节点
for (; p!=q; p = p.next, q = q.next) ;
return p;
}
还有一种更6的操作,是LeetCode上一个SEU.FidGet的网友的做法,考虑到作者的主权问题,请大家访问
https://leetcode-cn.com/problems/intersection-of-two-linked-lists/comments/可以查看哈