码迷,mamicode.com
首页 > 其他好文 > 详细

【LeetCode每天一题】Linked List Cycle II(循环链表II)

时间:2019-05-31 19:23:13      阅读:102      评论:0      收藏:0      [点我收藏+]

标签:nts   快慢指针   mod   for   http   init   lis   linked   存在   

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指向的节点就为环的入口节点。       

【LeetCode每天一题】Linked List Cycle II(循环链表II)

标签:nts   快慢指针   mod   for   http   init   lis   linked   存在   

原文地址:https://www.cnblogs.com/GoodRnne/p/10957057.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!