一个链表存表,如果存在环,则返回入环节点,否则返回null
快慢指针 相遇即是 入环节点 (快慢指针可以求中点)
/**
* Definition for singly-linked list.
* class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public ListNode detectCycle(ListNode head) {
if(head==null ){
return null;
}
ListNode slow=head;
ListNode fast=head;
while(slow!=null && fast!=null){
slow=slow.next;
fast=fast.next;
if(fast==null){
return null;
}else{
fast=fast.next;
}
if(slow==fast){
break;
}
}
if(fast==null){
return null;
}
ListNode ptr=head;//第三个指针
while(ptr!=slow){
ptr=ptr.next;
slow=slow.next;
}
return ptr;
}
}
两个链表,如果相交,则返回相交点,否则返回null
方法1
求链表长度,然后根据长度差值,用两个指针遍历看是否会相遇
public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
int lenA=0,lenB=0;
ListNode pa=headA,pb=headB;
while(pa!=null){
pa=pa.next;
lenA++;
}
while(pb!=null){
pb=pb.next;
lenB++;
}
if(lenA==0 || lenB==0){
return null;
}
ListNode s=headA,l=headB;
if(lenA>lenB){
l=headA;
s=headB;
}
for(int i=0;i<Math.abs(lenB-lenA);i++){
l=l.next;
}
while(s!=null && l!=null){
if(s==l){
return s;
}
s=s.next;
l=l.next;
}
return null;
}
方法2
两个指针,依次遍历两个链表
ublic ListNode getIntersectionNode(ListNode headA, ListNode headB) {
ListNode p1=headA;
ListNode p2=headB;
if(p1==null || p2==null){
return null;
}
while(p1!=null && p2!=null){
if(p1==p2){
return p1;
}
p1=p1.next;
p2=p2.next;
if(p1==null){
p1=headB;
}else if(p2==null){
p2=headA;
}
}
return null;
}