[Leetcode]Linked List Cycle

来源:互联网 发布:mac 待机设置 编辑:程序博客网 时间:2024/05/05 21:30

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

Follow up:

Can you solve it without using extra space?

比较常见的一道题  cracking code interview上也有~ 判断链表里有没有cycle    常见的方法是维护两个指针slow和fast,两个指针以不同的速度往前走,如果两个指针能相遇,则说明有cycle  这题不用判断cycle的起点,所以较容易

class Solution:    # @param head, a ListNode    # @return a boolean    def hasCycle(self, head):        if head is None: return False        fast, slow = head, head        while fast != None and fast.next != None:            fast, slow = fast.next.next, slow.next            if fast == slow:                return True        return False


0 0
原创粉丝点击