链表中环的入口节点

 1 # -*- coding:utf-8 -*-
 2 # class ListNode:
 3 #     def __init__(self, x):
 4 #         self.val = x
 5 #         self.next = None
 6 class Solution:
 7     def EntryNodeOfLoop(self, pHead):
 8         # write code here
 9         #先判断是不是有环,用快慢指针(一个正常走,一个每次走两步),如果有环必然会相遇
10         if pHead == None:
11             return None
12         meetingnode = self.MeetingNode(pHead)
13         if meetingnode == None:#如果判断无交点的的情况
14             return None
15         nodeslop = 1
16         node1 = meetingnode  #如果有交点,返回交点就够了。环的节点数比运行次数多1 
17         while node1.next != meetingnode:
18             node1 = node1.next
19             nodeslop += 1
20         node1 = pHead   #原链表一直没动
21         for i in range(nodeslop):#两个指针开始走,当先让一个指针走环内节点数的步数时,另一个节点再走,此时相遇的点恰好是成环第一个节点
22             node1 = node1.next
23         node2 = pHead
24         while node1 != node2:
25             node1 = node1.next
26             node2 = node2.next
27         return node1
28         
29     def MeetingNode(self, pHead):
30         slow = pHead.next
31         if slow == None:
32             return None
33         fast = slow.next
34         while fast != None:
35             if slow == fast:
36                 return fast
37             slow = slow.next
38             fast = fast.next
39             if fast != None:  #不是循环只会运行一次
40                 fast = fast.next
41         return None

 

posted @ 2019-05-07 21:37  Parallax  阅读(82)  评论(0编辑  收藏  举报