如果一个链表中包含环,如何找出环的入口节点?
分解成3个步骤:找出环中任意一个节点、得到环中节点的数目、找到环的入口节点。
class Solution:
def entry_node_of_loop(self, node):
if not node:
return node
node_number_of_cycle = self.is_cycle(node)
if not node_number_of_cycle:
return None
front, rear = node, node
for ni in range(node_number_of_cycle):
rear = rear.next
while front != rear:
front = front.next
rear = rear.next
return front
def is_cycle(self, node):
slow, fast = node, node.next
if fast:
fast = fast.next
while fast:
if fast == slow:
break
slow = slow.next
fast = fast.next
if fast:
fast = fast.next
else:
return None
compare = slow
slow, count = slow.next, 1
while slow != compare:
count += 1
slow = slow.next
return count
st = Solution()
node = ListNode(1)
node.next = ListNode(2)
node.next.next = ListNode(3)
node.next.next.next = ListNode(4)
node.next.next.next.next = ListNode(5)
node.next.next.next.next = node.next
print(st.entry_node_of_loop(node).val)
(最近更新:2019年07月16日)