LeetCode每天一题Linked List Cycle II(循环链表II)
Posted goodrnne
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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指向的节点就为环的入口节点。
以上是关于LeetCode每天一题Linked List Cycle II(循环链表II)的主要内容,如果未能解决你的问题,请参考以下文章
LeetCode每天一题Insertion Sort List(使用插入法对链表进行排序)
LeetCode每天一题Remove Duplicates from Sorted List(移除有序链表中的重复数字)
LeetCode每天一题 Remove Duplicates from Sorted List II(移除有序链表中重复的节点)