快慢指针
public class Solution { public boolean hasCycle(ListNode head) { //快慢指针 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; } }环形链表2
给定一个链表,返回链表开始入环的第一个节点。 如果链表无环,则返回 null。
public class Solution { public ListNode detectCycle(ListNode head) { ListNode fast = head; ListNode slow = head; boolean hasCycle = false; while(fast!=null&&fast.next!=null){ fast=fast.next.next; slow=slow.next; if(fast==slow){ hasCycle = true; break; } } if(hasCycle){ ListNode p = head; ListNode q = slow; while(p!=q){ p=p.next; q=q.next; } return q; }else{ return null; } } }