1、前言
题目描述2、思路
若相交,链表A: a+c, 链表B : b+c. a+c+b+c = b+c+a+c 。则会在公共处c起点相遇。若不相交,a +b = b+a 。因此相遇处是NULL。
3、代码
public class Q160_GetIntersectionNode {
public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
if(headA == null || headB == null){
return null;
}
ListNode p = headA, q = headB;
while(p != q){
p = p == null ? headB : p.next;
q = q == null ? headA : q.next;
}
return p;
}
public static void main(String[] args) {
ListNode l1 = new ListNode(4);
ListNode l2 = new ListNode(1);
ListNode l3 = new ListNode(8);
ListNode l4 = new ListNode(4);
ListNode l5 = new ListNode(5);
l1.next = l2;
l2.next = l3;
l3.next = l4;
l4.next = l5;
ListNode l6 = new ListNode(7);
l6.next = l3;
ListNode listNode = new Q160_GetIntersectionNode().getIntersectionNode(l1, l6);
System.out.println(listNode.val);
}
}
网友评论