链表中环的入口点( python实现 )
一、题目描述
题目:链表中环的入口点
如果一个链表中包含环,如何找出环的入口节点。
二、解题思路
暂略。(此处主要作为书中python实现补充)
三、代码实现
MeetingNode() 函数主要是用于判断链表中环的存在情况。若存在环,则返回快慢指针相遇的节点,若不存在,则返回 None。
def MeetingNode(pHead):
if pHead is None:
return
pSlow = pHead
pFast = pHead.next
while pSlow is not None and pFast is not None:
if pFast == pSlow:
return pSlow
pSlow = pSlow.next
pFast = pFast.next
if pFast is not None:
pFast = pFast.next
return
在找到环中任意一个节点后,就能得出环中节点数目,并找到入口节点。相应代码如下:
def EntryNodeOfLoop(pHead):
meetingNode = MeetingNode(pHead)
if meetingNode is None:
return
numOfNodesInLoop = 1
pNode = meetingNode
while pNode.next != meetingNode:
pNode = pNode.next
numOfNodesInLoop = numOfNodesInLoop+1
pNode1 = pHead
for i in range(numOfNodesInLoop):
pNode1 = pNode1.next
pNode2 = pHead
while pNode1 != pNode2:
pNode1 = pNode1.next
pNode2 = pNode2.next
return pNode1
以下用一种简单粗暴的方式,快速定义一个测试样例,供大家参考。
定义一个链表的数据结构
class LinkedListNode():
def __init__ (self, value = None, next = None):
self.value = value
self.next = next
# 单链表类
class SingleLinkedList():
# 初始化
def __init__ (self):
self.head = None
# 判断链表是否为空
def is_empty(self):
if self.head is None:
return True
# 创建一个新链表节点
def add(self,new_value):
node = LinkedListNode(new_value,self.head)
self.head = node
# 增加一个新的结点
def append(self,new_value):
node = LinkedListNode(new_value)
if self.is_empty():
self.head = node
else:
node.next = self.head
self.head = node
自定义一个链表类,首先生成一个链表: 0->1->2->3->4->5->6->7->8->9,然后将链表最后一个节点的 next 指向第5个节点,即这里值为4的节点。(以下代码即为这里提到的简单粗暴的核心)
>>> SLL = SingleLinkedList()
>>> for i in range(9,-1,-1):
SLL.append(i)
>>> pHead = SLL.head
>>> pNode = pHead
>>> for i in range(4): # 这里若是改为6,那么文末的输出也为6,可自行测试
pNode = pNode.next
>>> pNodeEnd = pHead
>>> for i in range(9):
pNodeEnd = pNodeEnd.next
>>> pNodeEnd.next = pNode
然后利用自定义的样例 测试上面的函数 EntryNodeOfLoop() 函数如下:
>>> EntryNodeOfLoop(pHead).value
Out:
4