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

转载于:https://www.cnblogs.com/GoodRnne/p/10957057.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值