leetcode -- Linked List Cycle -- 重点

来源:互联网 发布:mac os windows双系统 编辑:程序博客网 时间:2024/06/03 16:01

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

参考http://www.cnblogs.com/zuoyuan/p/3701639.html

一开始我错误的code:

class Solution(object):    def hasCycle(self, head):        """        :type head: ListNode        :rtype: bool        """        if not head : return False        slow, fast = head, head        while fast and fast.next and fast != slow:#这里这个条件fast!=slow,使得在一开始就无法进入循环            slow = slow.next            fast = fast.next.next        if fast == None or fast.next == None:            return False        else:            return True

正确的code:

class Solution(object):    def hasCycle(self, head):        """        :type head: ListNode        :rtype: bool        """        if not head : return False        slow, fast = head, head        while fast.next and fast.next.next:#这里用fast and fast.next也可以            slow = slow.next            fast = fast.next.next            if slow == fast:                return True        return False
0 0
原创粉丝点击