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

     1 # -*- coding:utf-8 -*-
     2 # class ListNode:
     3 #     def __init__(self, x):
     4 #         self.val = x
     5 #         self.next = None
     6 class Solution:
     7     def EntryNodeOfLoop(self, pHead):
     8         # write code here
     9         #先判断是不是有环,用快慢指针(一个正常走,一个每次走两步),如果有环必然会相遇
    10         if pHead == None:
    11             return None
    12         meetingnode = self.MeetingNode(pHead)
    13         if meetingnode == None:#如果判断无交点的的情况
    14             return None
    15         nodeslop = 1
    16         node1 = meetingnode  #如果有交点,返回交点就够了。环的节点数比运行次数多1 
    17         while node1.next != meetingnode:
    18             node1 = node1.next
    19             nodeslop += 1
    20         node1 = pHead   #原链表一直没动
    21         for i in range(nodeslop):#两个指针开始走,当先让一个指针走环内节点数的步数时,另一个节点再走,此时相遇的点恰好是成环第一个节点
    22             node1 = node1.next
    23         node2 = pHead
    24         while node1 != node2:
    25             node1 = node1.next
    26             node2 = node2.next
    27         return node1
    28         
    29     def MeetingNode(self, pHead):
    30         slow = pHead.next
    31         if slow == None:
    32             return None
    33         fast = slow.next
    34         while fast != None:
    35             if slow == fast:
    36                 return fast
    37             slow = slow.next
    38             fast = fast.next
    39             if fast != None:  #不是循环只会运行一次
    40                 fast = fast.next
    41         return None
  • 相关阅读:
    2021NUAA暑假集训 Day3 题解
    2021NUAA暑假集训 Day2 题解
    2021NUAA暑期模拟赛部分题解
    CodeForces 1038D Slime
    UVA 11149 Power of Matrix
    UVA 10655 Contemplation! Algebra
    UVA 10689 Yet another Number Sequence
    HDU 4549 M斐波那契数列
    HDU 4990 Reading comprehension
    CodeForces 450B Jzzhu and Sequences
  • 原文地址:https://www.cnblogs.com/Henry-ZHAO/p/12725300.html
Copyright © 2011-2022 走看看