建设网站公司哪家好软件网站排行榜
问题描述:
- Given a linked list, determine if it has a cycle in it.
思路:
-
采用快慢指针法,快指针每次前进两个节点,慢指针每次前进一个节点
-
无环条件:node.next=NULL
-
有环条件:快指针指向的节点=慢指针指向的节点
代码:
# 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"""slow=fast=headwhile True:try:fast=fast.next.nextslow=slow.nextif fast==slow:return Trueexcept:return False
结果:
Runtime: 40 ms, faster than 100.00% of Python online submissions for Linked List Cycle.