zoukankan      html  css  js  c++  java
  • [leetcode]Linked List Cycle @ Python

    原题地址:http://oj.leetcode.com/problems/linked-list-cycle/

    题意:判断链表中是否存在环路。

    解题思路:快慢指针技巧,slow指针和fast指针开始同时指向头结点head,fast每次走两步,slow每次走一步。如果链表不存在环,那么fast或者fast.next会先到None。如果链表中存在环路,则由于fast指针移动的速度是slow指针移动速度的两倍,所以在进入环路以后,两个指针迟早会相遇,如果在某一时刻slow==fast,说明链表存在环路。

    代码:

    # 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
  • 相关阅读:
    react.js
    shell if,case,for,while语法
    shell判断文件类型和权限
    shell编程之sed语法
    php魔术方法__SET __GET
    git 忽略文件.gitignore
    php设置错误,错误记录
    linux ifconfig显示 command not found
    数据库备份与恢复
    mysql主要技术
  • 原文地址:https://www.cnblogs.com/zuoyuan/p/3701639.html
Copyright © 2011-2022 走看看