zoukankan      html  css  js  c++  java
  • 25.leetcode142_linked_list_cycle_II

    1.题目描述

    Given a linked list, return the node where the cycle begins. If there is no cycle, return null.

    Note: Do not modify the linked list.

    给出一个链表,返回链表环的起点。没有环的话,返回null(注:不使用额外的空间)

    2.题目分析

    这个题是上一题的进阶版。除了要判断链表是否有环外,还要找出它的起点。

    3.解题思路

    ①判圈算法:使用双指针,一个快指针和一个慢指针同时遍历,如果遇到快指针与慢指针相同的情况,说明存在链表环。如果遇到指针为空的情况,则不存在链表环

    ②因为快指针速度是慢指针的二倍,而当两指针相遇时,快指针比慢指针快一个链表环的长度。

    (用Ai画的示意图,应该能看懂,过多不解释)

     1 # Definition for singly-linked list.
     2 # class ListNode(object):
     3 #     def __init__(self, x):
     4 #         self.val = x
     5 #         self.next = None
     6 
     7 class Solution(object):
     8     def detectCycle(self, head):
     9         """
    10         :type head: ListNode
    11         :rtype: ListNode
    12         """
    13         if head==None:
    14             return None
    15         p1=head
    16         p2=head
    17         l1=0
    18         l2=0
    19         while p1.next!=None:
    20             p1=p1.next.next
    21             l1+=2
    22             if p1==None:
    23                 return None
    24             if p1==p2:
    25                 l=l1-l2
    26                 temp=head #设置双指针
    27                 p=head
    28                 for i in range(0,l):  #p比temp快整一个链环的长度
    29                     p=p.next
    30                 while temp.next!=None: #开始遍历链表
    31                     if temp==p: #相等返回p/temp
    32                         return p
    33                     else: #不相等,同时前进一个节点
    34                         temp=temp.next
    35                         p=p.next
    36             else:
    37                 p2=p2.next
    38                 l2+=1
    39         return None
  • 相关阅读:
    ASP.NET---创建自定义Web控件小结
    ASP.NET---使用Asp.NET开发三层架构的应用程序
    poj 1847 最短路简单题,dijkstra
    HDU 1102 最小生成树裸题,kruskal,prim
    poj 2239 二分图最大匹配,基础题(待补)
    HDU 1520 树形dp裸题
    HDU 2089 简单数位dp
    poj 3254 状压dp入门题
    HDU 1710 二叉树遍历,输入前、中序求后序
    Poj 3250 单调栈
  • 原文地址:https://www.cnblogs.com/19991201xiao/p/8445579.html
Copyright © 2011-2022 走看看