Leetcode #141 Linked List Cycle Python

来源:互联网 发布:松下fpwin编程手册 编辑:程序博客网 时间:2024/06/01 08:05

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

Follow up:

Can you solve it without using extra space?

Difficulty:Medium

不占用额外地址的做法,两个node一个每次跳一次,一个每次跳两下next,如果碰到none就返回False,如果这个两个node重合了就说明有一个circle。

# 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        """        p = head        pNext=head                while (p is not None) and (pNext is not None):            if p.next is None or pNext.next is None:                return False            p = p.next            pNext = pNext.next.next            if p==pNext:                return True        return False


0 0