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

 

posted @ 2018-09-19 11:24  耐烦不急  阅读(295)  评论(0编辑  收藏  举报