[leetcode]Linked List Cycle @ Python
2020-11-24 09:37
标签:style blog class code java javascript ext color rgb for 代码 原题地址:http://oj.leetcode.com/problems/linked-list-cycle/ 题意:判断链表中是否存在环路。 解题思路:快慢指针技巧,slow指针和fast指针开始同时指向头结点head,fast每次走两步,slow每次走一步。如果链表不存在环,那么fast或者fast.next会先到None。如果链表中存在环路,则由于fast指针移动的速度是slow指针移动速度的两倍,所以在进入环路以后,两个指针迟早会相遇,如果在某一时刻slow==fast,说明链表存在环路。 代码: [leetcode]Linked List Cycle @ Python,搜素材,soscw.com [leetcode]Linked List Cycle @ Python 标签:style blog class code java javascript ext color rgb for 代码 原文地址:http://www.cnblogs.com/zuoyuan/p/3701639.html# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
# @param head, a ListNode
# @return a boolean
def hasCycle(self, head):
if head == None or head.next == None:
return False
slow = fast = head
while fast and fast.next:
slow = slow.next
fast = fast.next.next
if slow == fast:
return True
return False
文章标题:[leetcode]Linked List Cycle @ Python
文章链接:http://soscw.com/essay/22367.html