链表环路2--Linked List Cycle II

https://leetcode.com/problems/linked-list-cycle-ii/

Linked List Cycle II

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

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

题目:如果链表存在环路,找到环路的起始结点。

注:参加博客http://www.cnblogs.com/zuoyuan/p/3701877.html 写的很详细

     经过推到得知,当slow从head出发,fast从相遇点出发,一步一步前进,它们会再次相遇在起始结点。

 1 # Definition for singly-linked list.
 2 # class ListNode:
 3 #     def __init__(self, x):
 4 #         self.val = x
 5 #         self.next = None
 6 
 7 class Solution:
 8     # @param head, a ListNode
 9     # @return a list node
10     def detectCycle(self, head):
11         if head==None or head.next==None:
12             return None
13         slow=fast=head
14         while fast and fast.next:         #找到slow和fast的相遇点,让fast待在那里
15             slow=slow.next
16             fast=fast.next.next
17             if slow==fast:
18                 break
19         if slow==fast:                    #不知前面跳出循环的原因是不满足while条件(无环),还是满足if而break(找到相遇点),所以要判断
20             slow=head                     #让slow回到head
21             while slow!=fast:
22                 slow=slow.next            #fast和slow同时走直到while不满足(即相遇)
23                 fast=fast.next              
24             return slow                   #再次相遇点即为起点,返回该点
25         return None                       #对应if slow==fast的else情况,即无环,返回None

 

posted @ 2015-07-01 11:01  小榛子  阅读(110)  评论(0编辑  收藏  举报