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.

  • 相关阅读:
    SpringFramework中的BeanWrapper丶PropertyEditor
    Spring加载资源文件的方式
    kettle批量导入json数据
    Beanfactory与ApplicationContext
    fastjson的方法应用与java JSONObject
    算法 汽水瓶
    算法 简单密码
    算法 识别有效ip地址和掩码并做统计
    各类IP地址
    算法 密码验证合格程序
  • 原文地址:https://www.cnblogs.com/prmlab/p/6993390.html
Copyright © 2011-2022 走看看