zoukankan      html  css  js  c++  java
  • 【LeetCode每天一题】Linked List Cycle II(循环链表II)

    Given a linked list, return the node where the cycle begins. If there is no cycle, return null. To represent a cycle in the given linked list, we use an integer pos which represents the position (0-indexed) in the linked list where tail connects to. If pos is -1, then there is no cycle in the linked list.

    Note: Do not modify the linked list.

    Example 1:

    Input: head = [3,2,0,-4], pos = 1
    Output: tail connects to node index 1
    Explanation: There is a cycle in the linked list, where tail connects to the second node.
    

    Example 2:

    Input: head = [1,2], pos = 0
    Output: tail connects to node index 0
    Explanation: There is a cycle in the linked list, where tail connects to the first node.
    

    Example 3:

    Input: head = [1], pos = -1
    Output: no cycle
    Explanation: There is no cycle in the linked list.
    

    思路


      这道题的主要思路就是我们先判断链表是否存在环(快慢指针快指针每次移动两步,慢指针每次移动一步,如果存在环的话,两个指针会重合),然后找出这个环一共有几个节点(从重合的节点开始遍历一圈得到环中的节点数),最后从头开始设置快慢指针,快指针先移动环的节点数步,然后快慢指针一起移动。当快慢指针重合时,指向的节点就表示环的入口节点。时间复杂度未O(n), 空间复杂度为O(1)。

    解决代码


     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 not head or not head.next:
    14             return None
    15         one, two = head, head.next       # 设置快慢指针
    16         while one is not two:            # 判断是否存在环
    17             if not two or not two.next:
    18                 return None
    19             one = one.next
    20             two = two.next.next
    21         
    22         count = 1             # 记录环中节点个数
    23         while one is not two.next:   
    24             two = two.next
    25             count += 1
    26         
    27         one, two = head, head      # 重新指向头节点
    28         while count > 0:          # two指针先移动count次
    29             two = two.next
    30             count -= 1
    31         while one is not  two:      # 然后one,two指针一起移动。
    32             one = one.next
    33             two = two.next
    34         return one           # 返回one指向的节点就为环的入口节点。       
  • 相关阅读:
    javascript基础之两种函数的定义方法
    与input有关的一些操作
    SpringMVC(八) RequestMapping HiddenHttpMethodFilter
    SpringMVC(七) RequestMapping 路径中带占位符的URL
    SpringMVC(六) RequestMapping 路径中ant风格的通配符
    SpringMVC(五) RequestMapping 请求参数和请求头
    SpringMVC(四) RequestMapping请求方式
    SpringMVC(三) RequestMapping修饰类
    SpringMVC(二) SpringMVC Hello World
    SpringMVC(一) SpringMVC概述
  • 原文地址:https://www.cnblogs.com/GoodRnne/p/10957057.html
Copyright © 2011-2022 走看看