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

18-142. Linked List Cycle II

时间:2019-06-09 10:05:20      阅读:108      评论:0      收藏:0      [点我收藏+]

标签:NPU   turn   mod   def   sel   pytho   dex   out   code   

题目描述:

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.

技术图片

 

Follow up:
Can you solve it without using extra space?

代码实现:

 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         try:
14             fast = head.next
15             slow = head
16             while fast is not slow:
17                 fast = fast.next.next
18                 slow = slow.next
19         except:
20             # if there is an exception, we reach the end and there is no cycle
21             return None
22 
23         # since fast starts at head.next, we need to move slow one step forward
24         slow = slow.next
25         while head is not slow:
26             head = head.next
27             slow = slow.next
28 
29         return head

参考资料:https://leetcode.com/problems/linked-list-cycle-ii/discuss/44783/Share-my-python-solution-with-detailed-explanation

18-142. Linked List Cycle II

标签:NPU   turn   mod   def   sel   pytho   dex   out   code   

原文地址:https://www.cnblogs.com/tbgatgb/p/10992375.html

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