Leetcode141. Linked List Cycle

Posted 于淼

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Leetcode141. Linked List Cycle相关的知识,希望对你有一定的参考价值。

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

Follow up:
Can you solve it without using extra space?

Tips:判断一个链表中是否有环。

思路:设置两个指针,一个快(fast)一个慢(slow),fast指针每次走两步,slow每次走一步。当两个指针相遇,即存在环。若链表中没有环,则fast指针先到达null;

public boolean hasCycle(ListNode head) {
        if (head == null || head.next == null)
            return false;
        boolean hasCy = false;
        ListNode fast = head;
        ListNode slow = head;
        while (fast!=null) {
            if(fast.next!=null){
                fast=fast.next;
                if(fast.next!=null){
                    fast=fast.next;
                    slow=slow.next;
                    if (fast == slow) {
                        hasCy = true;
                        break;
                    }
                }else
                    return false;
            }else
                return false;
        }
        return hasCy;
    }

 


以上是关于Leetcode141. Linked List Cycle的主要内容,如果未能解决你的问题,请参考以下文章

leetcode-141. Linked List Cycle

LeetCode 141. Linked List Cycle

[Leetcode]141. Linked List Cycle

LeetCode 141, 142. Linked List Cycle I+II

LeetCode 141 Linked List Cycle

[Leetcode]141. Linked List Cycle