呐。这个题目自己想出来的方法是,遍历一个点就把这个点的NEXT指针改掉。
在this.next变成被改值||this.next 是None(队尾)时结束遍历循环。
代码如下。(开始时因为弄反返回值(T or F .跑错了好几下。所以。【看清题目】呐大妹砸!!
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def hasCycle(self, head):
"""
:type head: ListNode
:rtype: bool
"""
if (head is None) or (head.next is None):
return False
else:
this = head
while (this.next != head) and (this.next is not None):
tmp = this.next
this.next = head
this = tmp
if this.next == head :
return True
else:
return False
可是这个方法太蠢&&太慢&&太low了。。。
于是看了下discuss. 看到了一个fast&slow俩指针的方法。
每次fast比slow 多move一个next。 每天追赶一点点。追到了就是有圈嘛~
代码如下啦((可是居然还在python的后28%左右。。。难道还有更高大上的方法?((猜想应该是我的实现方法不够优化吧。。。
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def hasCycle(self, head):
"""
:type head: ListNode
:rtype: bool
"""
if (head is None) or (head.next is None):
return False
else:
fast = head
slow = head
while(fast is not None and fast.next is not None):
fast = fast.next.next
slow = slow.next
if fast == slow :
return True
return False