23.链表中环的入口节点

题目描述

给一个链表,若其中包含环,请找出该链表的环的入口结点,否则,输出null。

思路:

1.首先需要判断链表中是否包含环,可以用一快一慢的两个指针,当快的指针追上慢的,说明有环;如果当快的指针到达了尾结点还没有和慢的指针相遇,那么久说明没有环。

2.其次要找出环的入口节点。假设环中有n个节点,从链表的开始设快慢两个指针,让快的指针先走n步,然后两个指针以相同速度移动,当快慢指针相遇时恰好就是环的入口节点。

3.如何得到环中节点的个数呢?当1中快慢指针相遇时肯定是在环内,从这个节点出发,一边继续向前移动一边计数,当再次回到这个节点时,就可以得到环中节点数了。

python题解:

# -*- 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:
            return None
        mNode=self.judgeLoopRecordMeeting(pHead)
        if mNode:
            count=self.LoopNodeCount(mNode) #count为节点个数
            pPre=pHead
            pEnd=pHead
            for i in range(0,count):  #pPre先走count步
                pPre=pPre.next
            while pPre!=pEnd:
                pPre=pPre.next
                pEnd=pEnd.next
            return pPre
        else:
            return None

    def judgeLoopRecordMeeting(self,pHead):  #如果有循环,返回相遇的节点
        pFast=pHead
        pSlow=pHead
        while pFast.next:
            pFast=pFast.next.next
            pSlow=pSlow.next
            if pFast==pSlow:
                return pSlow
        return None
    
    def LoopNodeCount(self,pMeet): #找到循环中的节点个数
        count=1   #注意这里count的计数
        N=pMeet
        while N.next!=pMeet:
            N=N.next
            count=count+1
        return count
            
      

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值