题目
解答
思路
利用双指针的方法,通过使用具有不同速度的快、慢两个指针遍历链表,若相遇则为true,不相遇则为false。
代码
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def hasCycle(self, head):
if(head == None or head.next == None):
return False
node1 = head
node2 = head.next
while(node1 != node2):
if(node2 == None or node2.next == None):
return False
node1 = node1.next
node2 = node2.next.next
return True
结果
时间复杂度O(n)