链表中环的入口结点[剑指offer]

2 篇文章 0 订阅

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

分析:
1.设订两个指针,pFast和pSlow,pFast每次走两个结点,pSlow每次一个结点
2.如果有环,pFast和pSlow相遇一定是在环内
3.相遇以后,pSlow不动,pFast回到头结点.
4.pFast和pSlow一起走,每次都走一个结点
5.当pFast和pSlow再次相遇的时候就是入口.

算法推倒:
在这里插入图片描述
C++代码:

/*
struct ListNode {
    int val;
    struct ListNode *next;
    ListNode(int x) :
        val(x), next(NULL) {
    }
};
*/
class Solution {
public:
    ListNode* EntryNodeOfLoop(ListNode* pHead)
    {
        if(pHead == NULL || pHead->next == NULL || pHead->next->next == NULL)
            return NULL;
        ListNode* p2 = pHead->next->next; //因为后面是p2!=p1所以不能从头结点开始
        ListNode* p1 = pHead->next;
        while(p2 != p1)
        {
            if(p2 != NULL || p2->next != NULL)
            {
                p2 = p2->next->next;
                p1 = p1->next;
            }
            else
            {
                return NULL;
            }
        }
        p2 = pHead;
        while(p1 != p2)
        {
            p2 = p2->next;
            p1 = p1->next;
        }
        return p2;
    }
};

python代码:

# -*- coding:utf-8 -*-
class ListNode:
    def __init__(self, x):
        self.val = x
        self.next = None
class Solution:
    def EntryNodeOfLoop(self, pHead):
        pFast = pHead
        pSlow = pHead
        while pFast != None and pFast.next != None:
            pFast = pFast.next.next
            pSlow = pSlow.next
            if pFast == pSlow:
                break
        if pFast == None or pFast.next == None:
            return None
        pFast = pHead
        while pFast != pSlow:
            pFast = pFast.next
            pSlow = pSlow.next
        return pFast
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值