/**
* Definition for singly-linked list.
* class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public boolean hasCycle(ListNode head) {
if(head==null)
{
return false;
}
ListNode fast = head;
ListNode slow = head;
while(fast!=null&&fast.next!=null){
fast = fast.next.next;
slow = slow.next;
if(fast==slow)
{
return true;
}
}
return false;
}
}
/*
public class ListNode {
int val;
ListNode next = null;
ListNode(int val) {
this.val = val;
}
}
*/
public class Solution {
public ListNode EntryNodeOfLoop(ListNode pHead) {
ListNode slow = hasCycle(pHead);
if(slow==null){
return null;
}else{
ListNode fast=slow;
slow = pHead;
while(slow!=fast)
{
slow=slow.next;
fast =fast.next;
}
return slow;
}
}
public ListNode hasCycle(ListNode head) {
if(head==null)
{
return null;
}
ListNode fast = head;
ListNode slow = head;
while(fast!=null&&fast.next!=null){
fast = fast.next.next;
slow = slow.next;
if(fast==slow)
{
return slow;
}
}
return null;
}
}
总结:链表中环的问题主要是通过快慢指针来解决
第一类:判断是否有环:快慢指针如果有环一定会相遇
第二类:判断环的入口:快慢指针,当快慢指针第一次相遇时,将快指针指向头结点,然后变为慢指针,两个指针都各走一步,当再次相遇时就是环的入口。
最后几个节点属于简单为题,同样可以用快慢指针来解决,快指针先走n个节点即可。