Given a linked list, determine if it has a cycle in it.
Follow up:
Can you solve it without using extra space?
LeetCode:链接
和剑指Offer_编程题55:链表中环的入口结点是一样的。快慢指针思想,慢指针一次走一步,快指针一次走两步,如果快慢指针相遇说明有环。
但是在判断指针条件的时候,while twoStep.next.next and oneStep.next就出现问题了,在剑指offer的时候这种是可以AC过去的,但是LeetCode就得写成twoStep and twoStep.next!!!
# 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 not head:
return False
oneStep = head
twoStep = head
'''while oneStep.next and twoStep.next.next 在剑指offer是可以ac的 LeetCode过不去'''
while twoStep and twoStep.next:
oneStep = oneStep.next
twoStep = twoStep.next.next
if oneStep == twoStep:
return True
return False