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

    题目:

    一个链表中包含环,请找出该链表的环的入口结点。

    思路:

    1. 先说个定理:两个指针一个fast、一个slow同时从一个链表的头部出发,
    2. fast一次走2步,slow一次走一步,如果该链表有环,两个指针必然在环内相遇,
    3. 此时只需要把其中的一个指针重新指向链表头部,另一个不变(还在环内),
    4. 这次两个指针一次走一步,相遇的地方就是入口节点。

    python solution:

    # -*- coding:utf-8 -*-
    # class ListNode:
    #     def __init__(self, x):
    #         self.val = x
    #         self.next = None
    class Solution:
        def EntryNodeOfLoop(self, pHead):
            if pHead==None or pHead.next==None or pHead.next.next==None:
                return None
            low=pHead.next
            fast=pHead.next.next
            while low!=fast:
                if fast.next==None or fast.next.next==None:
                    return None
                low=low.next
                fast=fast.next.next
            fast=pHead
            while low!=fast:
                low=low.next
                fast=fast.next
            return fast
    

     另一种思路:

    # -*- coding:utf-8 -*-
    # class ListNode:
    #     def __init__(self, x):
    #         self.val = x
    #         self.next = None
    class Solution:
        def EntryNodeOfLoop(self, pHead):
            # write code here
            #遍历链表,环的存在,遍历遇见的第一个重复的即为入口节点
            tempList = []
            p = pHead
            while p:
                if p in tempList:
                    return p
                else:
                    tempList.append(p)
                p = p.next
    
  • 相关阅读:
    HTTPHelper
    C# 捕获全局亲测可用
    C# Excel的读写
    C# combox 绑定数据
    MySQL在CenterOS和Ubuntu的安装
    VMware虚拟机里的Centos7的IP
    Docker安装和部署
    linux安装git方法(转)
    mysql安装最后一步 Apply Security Settings 出错
    Linux下安装MySQL
  • 原文地址:https://www.cnblogs.com/tianqizhi/p/9673597.html
Copyright © 2011-2022 走看看