zoukankan      html  css  js  c++  java
  • 141. Linked List Cycle

    https://leetcode.com/problems/linked-list-cycle/#/description

    Given a linked list, determine if it has a cycle in it.

    Follow up:
    Can you solve it without using extra space?

    Sol:

    To solve this problem we will have two markers traversing through the list. marker1 and marker2. We will have both makers begin at the first node of the list and traverse through the linked list. However the second marker, marker2, will move two nodes ahead for every one node that marker1 moves.

    By this logic we can imagine that the markers are "racing" through the linked list, with marker2 moving faster. If the linked list has a cylce and is circularly connected we will have the analogy of a track, in this case the marker2 will eventually be "lapping" the marker1 and they will equal each other.

    If the linked list has no cycle, then marker2 should be able to continue on until the very end, never equaling the first marker.

    Let's see this logic coded out:

    # 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
            """
    
            p_slow = head
            p_fast = head
            
            
            while p_fast != None and p_fast.next != None:
                p_slow = p_slow.next
                p_fast = p_fast.next.next
                if p_slow == p_fast:
                    return True
            return False
                

    Note:

    1 Intialize two pointers by setting them as input variable head or node.

    2 To advance pointers, the right syntax is;

    pointer = pointer.next

    It update itself.... do not forget to intialize them beforehand.

  • 相关阅读:
    Centos7安装lnmp环境
    超酷播放器使用弹幕
    Thinkphp通过phpqrcode实现网址验证码
    特征选择
    决策树
    数据库与数据仓库的区别实际讲的是OLTP与OLAP的区别
    ETL 的一些概念
    ETL讲解
    均值、方差、协方差、协方差矩阵、特征值、特征向量
    浅谈梯度下降法
  • 原文地址:https://www.cnblogs.com/prmlab/p/6993390.html
Copyright © 2011-2022 走看看