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

25.leetcode142_linked_list_cycle_II

时间:2018-02-12 22:22:58      阅读:202      评论:0      收藏:0      [点我收藏+]

标签:相同   pos   object   col   inf   blog   info   body   进阶   

1.题目描述

Given a linked list, return the node where the cycle begins. If there is no cycle, return null.

Note: Do not modify the linked list.

给出一个链表,返回链表环的起点。没有环的话,返回null(注:不使用额外的空间)

2.题目分析

这个题是上一题的进阶版。除了要判断链表是否有环外,还要找出它的起点。

3.解题思路

①判圈算法:使用双指针,一个快指针和一个慢指针同时遍历,如果遇到快指针与慢指针相同的情况,说明存在链表环。如果遇到指针为空的情况,则不存在链表环

②因为快指针速度是慢指针的二倍,而当两指针相遇时,快指针比慢指针快一个链表环的长度。

技术分享图片

(用Ai画的示意图,应该能看懂,过多不解释)

 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 head==None:
14             return None
15         p1=head
16         p2=head
17         l1=0
18         l2=0
19         while p1.next!=None:
20             p1=p1.next.next
21             l1+=2
22             if p1==None:
23                 return None
24             if p1==p2:
25                 l=l1-l2
26                 temp=head #设置双指针
27                 p=head
28                 for i in range(0,l):  #p比temp快整一个链环的长度
29                     p=p.next
30                 while temp.next!=None: #开始遍历链表
31                     if temp==p: #相等返回p/temp
32                         return p
33                     else: #不相等,同时前进一个节点
34                         temp=temp.next
35                         p=p.next
36             else:
37                 p2=p2.next
38                 l2+=1
39         return None

 

25.leetcode142_linked_list_cycle_II

标签:相同   pos   object   col   inf   blog   info   body   进阶   

原文地址:https://www.cnblogs.com/19991201xiao/p/8445579.html

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