题解 | #链表中环的入口结点#

链表中环的入口结点

http://www.nowcoder.com/practice/253d2c59ec3e4bc68da16833f79a38e4

# -*- coding:utf-8 -*-
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None
class Solution:
    def MeetNode(self, pHead):
        if pHead==None:
            return None
        
        pSlow=pHead.next
        if pSlow==None:
            return None
        pFast=pSlow.next
        
        while pSlow.next!=None and pFast.next!=None:
            if pSlow==pFast:
                return pFast
            pSlow=pSlow.next
            pFast=pFast.next
            if pFast.next!=None:
                pFast=pFast.next
            elif pFast.next== None:
                return None
        
        return None
        
    
    def EntryNodeOfLoop(self, pHead):
        
        #1) 判断是否有环:若无环,返回None
        MeetingNode=self.MeetNode(pHead)
        if MeetingNode==None:
            return None
                                
        #2)若有环,得到环内节点个数
        tNode=MeetingNode
        num=1
        while tNode.next!=MeetingNode:
            tNode=tNode.next
            num+=1
        
        #3)仿照“链表中倒数K个节点”,用双指针得到入口节点。
        Node1=pHead
        Node2=pHead
        for i in range(num):
            Node1=Node1.next
        
        while Node1!=Node2:
            Node1=Node1.next
            Node2=Node2.next
        
        
        return Node1

全部评论

相关推荐

在写周报的打工人很独...:这个笔试昨天晚上做了一下,真难啊,前后端,ai全有
点赞 评论 收藏
分享
程序员花海:实习和校招简历正确格式应该是教育背景+实习+项目经历+个人评价 其中项目经历注意要体现业务 实习经历里面的业务更是要自圆其说 简历模板尽可能保持干净整洁 不要太花哨的
秋招吐槽大会
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务