给定两个单链表的头节点head1和head2,如何判断两个链表是否相交?相交的话返回true,不想交的话返回false。
先判断是否为单链表还是环形链表,之后再比较
import java.util.*;
/*
public class ListNode {
int val;
ListNode next = null;
ListNode(int val) {
this.val = val;
}
}*/
public class ChkIntersection {
public boolean chkInter(ListNode head1, ListNode head2, int adjust0, int adjust1) {
// write code here
ListNode node1=checkRink(head1);
ListNode node2=checkRink(head2);
if(node1==null&&node2!=null)
return false;
if(node1!=null&&node2==null)
return false;
if(node1==null&&node2==null)
return checkSingle(head1,head2);
//如果是环形链表,判断是否相交
if(node1!=null&&node2!=null){
if(node1==node2)//证明入环节点相同
return true;
ListNode tmp=node1.next;
while(tmp!=node1){//如果不同,这遍历node1,若在到达头节点之前找到node2相等的节点,则代表相交,若找不到则代表不想交
if(tmp==node2)
return true;
tmp=tmp.next;
}
return false;
}
return false;
}
//如果都是单链表,判断是否相交
public boolean checkSingle(ListNode head1,ListNode head2){
int lengthA=0;
int lengthB=0;
ListNode node1=head1;
while(node1!=null){
lengthA++;
node1=node1.next;
}
ListNode node2=head2;
while(node2!=null){
lengthB++;
node2=node2.next;
}
int count=0;
if(lengthA>lengthB){
count=lengthA-lengthB;
while(count>0){
head1=head1.next;
count--;
}
}
if(lengthA<lengthB){
count=lengthB-lengthA;
while(count>0){
head2=head2.next;
count--;
}
}
while(head1!=null){
if(head1==head2)
return true;
head1=head1.next;
head2=head2.next;
}
return false;
}
//判断是否为环形链表,若有,返回第一个节点
public ListNode checkRink(ListNode node){
ListNode fast=node;//每次遍历两个节点
ListNode slow=node;//每次遍历一个节点
while(fast!=null){
slow=slow.next;
if(fast.next==null)
return null;
fast=fast.next.next;
if(slow==fast)//如果相同,代表是环形
break;
}
if(fast==null)
return null;
ListNode tmp=node;
while(tmp!=slow){
tmp=tmp.next;
slow=slow.next;
}
return tmp;
}
}