141.Linked List Cycle (E)

https://leetcode.com/problems/linked-list-cycle/

1.Description(Medium)

Given a linked list, determine if it has a cycle in it.

Example

Given -21->10->4->5, tail connects to node index 1, return true

2.Code

典型的检测链表中有没有环的题目,

Version 1:用一个快慢指针fast=head.next; slow=head; 看会不会相遇,相遇就是true; fast每次走两步,slow每次走一步。

public boolean hasCycle(ListNode head) {  

        if(head==null ||head.next==null){
            return false;
        }

        ListNode slow=head;
        ListNode fast=head.next;//注意fast是head.next

        while(fast!=slow){
            //fast可能先结束
            if(fast==null ||fast.next==null){
                return false;
            }
            fast=fast.next.next;
            slow=slow.next;
        }
        return true;
    }

Version 2: fast=head; slow=head;

 public boolean hasCycle2(ListNode head){
        if(head==null || head.next==null){
            return false;
        }
        ListNode fast=head;
        ListNode slow=head;

        while(true){
            if(fast==null || fast.next==null){
                return false;
            }
            fast=fast.next.next;
            slow=slow.next;
            if(fast==slow){
                return true;
            }
        }
    }

Last updated

Was this helpful?