美文网首页LeetCode solutions
141. Linked List Cycle

141. Linked List Cycle

作者: 番茄晓蛋 | 来源:发表于2017-06-10 10:26 被阅读3次

**Description**Hints**Submissions**Solutions

Total Accepted: 177986
Total Submissions: 502453
Difficulty: Easy
Contributor: LeetCode

Given a linked list, determine if it has a cycle in it.
Follow up:Can you solve it without using extra space?

Hide Company Tags
Amazon Microsoft Bloomberg Yahoo
Hide Tags
Linked List Two Pointers
Hide Similar Problems
(M) Linked List Cycle II

    /*
      Use two pointers, slower and faster.
        slower moves step by step. faster moves two steps at time.
        if the Linked List has a cycle slower and faster will meet at some
        point.
    */
    public boolean hasCycle(ListNode head) {
        ListNode slow = new ListNode(0);
        ListNode fast = new ListNode(0);
        slow.next = head;
        fast.next = head;
        
        while (fast != null && fast.next != null) {
            fast = fast.next.next;
            slow = slow.next;
             if (fast == slow) {
                return true;
            }
        }
        return false;
    }

相关文章

网友评论

    本文标题:141. Linked List Cycle

    本文链接:https://www.haomeiwen.com/subject/gvpqqxtx.html