Given a linked list, determine if it has a cycle in it.
Follow up: Can you solve it without using extra space?
给定一个链表,确定它是否有一个循环。
跟进: 你能不用额外的空间解决它吗?
思路:
看最后一个结点是否指的是第一个结点。依次遍历
网上思路:https://blog.csdn.net/coder_orz/article/details/51516558
# 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
"""
print("===============================")
fast = slow = head
while fast and fast.next:
slow = slow.next
fast = fast.next.next
if slow == fast:
return True
return False
if __name__ == "__main__":
l = ListNode(1)
l.next = ListNode(2)
l.next.next = ListNode(1)
#l.next.next.next = l
c = Solution().hasCycle(l)
print(c)