leetcode笔记--Linked List Cycle

来源:互联网 发布:红蜘蛛软件卸载不了 编辑:程序博客网 时间:2024/05/01 04:32

题目:难度(Medium)

Given a linked list, determine if it has a cycle in it.
Follow up:
    Can you solve it without using extra space?
Tags:Linked List Two Pointers
Similar Problems:(M) Linked List Cycle II

分析:判断一个链表是否有环,可使用”龟兔赛跑“算法

代码实现:

# Definition for singly-linked list.# class ListNode(object):#     def __init__(self, x):#         self.val = x#         self.next = Noneclass Solution(object):    def hasCycle(self, head):        """        :type head: ListNode        :rtype: bool        """        #用龟兔赛跑算法        if head is None:            return False        p = head        q = p.next        while q is not None and p != q:            p = p.next            q = q.next            if q is not None:                q = q.next        if q is None:            return False        else:            return True


0 0
原创粉丝点击