链表_链表中环的入口结点
思路:参考答案
# -*- coding:utf-8 -*-
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def EntryNodeOfLoop(self, pHead):
# write code here
if not pHead or not pHead.next or not pHead.next.next:
return None
slow = pHead.next
fast = slow.next
# 找到相遇点
while fast != slow and fast and fast.next:
slow = slow.next
fast = fast.next.next
if slow == fast:
# 慢指针回到表头,快指针留在相遇点,二者同步往前直到相遇在入口结点
slow = pHead
while slow != fast:
fast = fast.next
slow = slow.next
return slow
return None
法二:在后面的半部分稍有差别。
# -*- coding:utf-8 -*-
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def EntryNodeOfLoop(self, pHead):
# write code here
if not pHead or not pHead.next:
return None
fast = pHead
slow = pHead
k = 0
go = True
while fast and go:
fast = fast.next.next
slow = slow.next
k += 1
if fast == slow:
go = False
break
if not go:
fast = pHead
slow = pHead
while k:
fast = fast.next
k -= 1
while fast != slow:
fast = fast.next
slow = slow.next
return fast
else:
return None
还有一种思路:
# -*- coding:utf-8 -*-
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def EntryNodeOfLoop(self, pHead):
# write code here
nodelist = []
while pHead:
if pHead in nodelist:
return pHead
else:
nodelist.append(pHead)
pHead = pHead.next