https://leetcode-cn.com/problems/intersection-of-two-linked-lists/
编写一个程序,找到两个单链表相交的起始节点。
package factory;
import base.ListNode;
/**
* @Auther: Jaryn
* @Date: 2019/12/9 22:31
* @Description: 相交链表
* https://leetcode-cn.com/explore/interview/card/top-interview-quesitons-in-2018/265/linked-list/1148/
* 算出A的长度,B的长度,A>B 则A先走a-b步,直到相遇
*/
public class GetIntersectionNode {
public static void main(String[] args) {
ListNode listNode1 = new ListNode(1);
ListNode listNode2 = new ListNode(2);
ListNode listNode3 = new ListNode(3);
ListNode listNode4 = new ListNode(4);
ListNode listNode5 = new ListNode(5);
ListNode listNode11 = new ListNode(11);
ListNode listNode12 = new ListNode(12);
ListNode listNode13 = new ListNode(13);
ListNode listNode14 = new ListNode(14);
ListNode listNode15 = new ListNode(15);
ListNode listNode16 = new ListNode(16);
// listNode1.setNext(listNode2);
listNode2.setNext(listNode3);
listNode3.setNext(null);
// listNode4.setNext(listNode5);
// listNode5.setNext(listNode13);
//
// listNode11.setNext(listNode12);
// listNode12.setNext(listNode13);
// listNode13.setNext(listNode14);
// listNode14.setNext(listNode15);
// listNode15.setNext(listNode16);
System.out.println(getIntersectionNode(listNode2, listNode3).getVal());
}
public static ListNode getIntersectionNode(ListNode headA, ListNode headB) {
if(headA == null || headB == null) {
return null;
}
if(headA == headB) {
return headA;
}
int alen = 1;
int blen = 1;
ListNode tempA = headA;
int com = 0;
while (tempA.getNext() != null) {
tempA = tempA.getNext();
alen +=1 ;
}
ListNode tempB = headB;
while (tempB.getNext() != null) {
tempB = tempB.getNext();
blen +=1 ;
}
tempA = headA;
tempB = headB;
if(alen > blen) {
com = alen - blen;
while (com > 0) {
tempA = tempA.getNext();
com--;
}
}else {
com = blen - alen;
while (com > 0) {
tempB = tempB.getNext();
com--;
}
}
while (tempA != null) {
if(tempA == tempB) {
return tempA;
}
tempA = tempA.getNext();
tempB = tempB.getNext();
}
return null;
}
}