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
            
                    
                
  • 相关阅读:
    wmi
    Python中基本同步原语的使用
    Python多线程的几种实现方式
    TCP/IP详解 卷1 第一章 概述
    对利用sqlmap获取os-shell过程的一次抓包分析
    12.19 Aggregate (GROUP BY) Functions
    13.2.9 SELECT 语法
    GitHack 源码分析
    CTF遇到的问题-长期更新
    在Windows server2008中搭建sqli-lab实验环境
  • 原文地址:https://www.cnblogs.com/ansang/p/12033405.html
Copyright © 2011-2022 走看看