微信:我拉你入高质量java群
package com.swh.maotobean;
import java.util.List;
//构造链表节点
class ListNode {
int val;
ListNode next = null;
ListNode(int val) {
this.val = val;
}
}
public class OverlapList {
//判断是否相交
public static boolean isPoint(ListNode list1, ListNode list2){
ListNode l1 = list1;
ListNode l2 = list2;
if(l1 == null || l2 == null){
return false;
}
while(l1.next != null){
l1 = l1.next;
}
while(l2.next != null){
l2 = l2.next;
}
return l1 == l2;
}
//获取链表的长度
public static int getLength(ListNode headNode){
ListNode countHead = headNode;
int count = 0;
while(headNode.next != null) {
countHead = countHead.next;
count++;
}
return count;
}
//获得交点
public static ListNode getPoint(ListNode node1, ListNode node2){
//首先判断两个链表的长度是相等,
int nodeLen1 = getLength(node1);
int nodeLen2 = getLength(node2);
//获取长度差
int gap = nodeLen2 - nodeLen1;
ListNode shortList = node1;
ListNode longList = node2;
if(nodeLen1 > nodeLen2){
shortList = node2;
longList = node1;
gap = nodeLen1 - nodeLen2;
}
for(int i = 0 ; i < gap ; i++){
longList = longList.next;
}
while(true){
//当遇到第一个相同的人节点的时候返回节点值
if(longList == shortList){
return longList;
}
longList = longList.next;
shortList = shortList.next;
}
}
}