zoukankan      html  css  js  c++  java
  • 剑指offer-链表中环的入口结点-链表-python ***

    题目描述

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

    思路

    第一步,用两个快慢指针找环中相汇点。分别用slowfast指向链表头部,slow每次走一步,fast每次走二步,直到fast == slow找到在环中的相汇点。
    第二步,找环的入口。当fast == slow时,假设slow走过x个节点,则fast走过2x个节点。设环中有n个节点,因为fastslow多走一圈(n个节点),所以有等式2x = n + x,可以推出n = x,即slow实际上走了一个环的步数。这时,我们让fast重新指向链表头部pHeadslow的位置不变,然后slowfast一起向前每次走一步,直到fast == slow,此时两个指针相遇的节点就是环的入口。

    # -*- 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  pHead is None:
                return None
            if pHead.next is None:
                return None
            p = pHead
            q = pHead.next
            while p!=q:
                if q.next is not None and q.next.next is not None:
                    p = p.next
                    q = q.next.next
                else:
                    break
            if p ==q:
                r = pHead
                p = p.next
                while r != p:
                    r = r.next
                    p = p.next
                return r 
            else:
                return None
            
                    
                
  • 相关阅读:
    sqlserver判断是否为数字的函数
    vs2013 旗舰版 密钥
    HttpWebRequest类与HttpRequest类的区别
    C#中HttpWebRequest的用法详解
    SQL Server查询优化方法(查询速度慢的原因很多,常见如下几种)
    随机数Random
    PadLeft 补零
    delphi Firemonkey ListBoxItem自绘
    windows自带杀毒防火墙
    IIS 更新EXE文件
  • 原文地址:https://www.cnblogs.com/ansang/p/12033405.html
Copyright © 2011-2022 走看看