【done】剑指offer——面试题56:链表中环的入口

力扣141142分别是判断是否有环及环入口。

链表是否有环

public class Solution {
    public boolean hasCycle(ListNode head) {
        ListNode slow = head, fast = head;
        while (fast != null && fast.next != null) {
            slow = slow.next;
            fast = fast.next.next;
            if (slow == fast) {
                return true;
            }
        }

        return false;
    }
}

链表环入口

public class Solution {
    public ListNode detectCycle(ListNode head) {
        ListNode slow = head, fast = head;
        while (fast != null && fast.next != null) {
            slow = slow.next;
            fast = fast.next.next;
            if (slow == fast) {
                break;
            }
        }
        if (fast == null || fast.next == null) {
            return null;
        }
        slow = head;
        while (slow != fast) {
            slow = slow.next;
            fast = fast.next;
        }

        return slow;
    }
}

##Solution1:
非常经典的快慢指针套路题。下面这个链接讲解的很详细。其实问题的关键在于为什么快指针的速度一定是慢指针的2倍,3倍或4倍行不行??
快慢指针是一类很经典的算法,在这里贴一个讲解的比较清楚的博客:
https://www.cnblogs.com/songdechiu/p/6686520.html

/*
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 == 0 || pHead->next->next == 0)
            return NULL;
        struct ListNode *slow = pHead->next, *fast = pHead->next->next; //slow走了1步到pHead->next的位置,fast走了2步
        while(fast != slow) {                                           //到了pHead->next->next的位置
            if(fast->next != NULL && fast->next->next != NULL) {
                slow = slow->next;
                fast = fast->next->next;
            }
            else 
                return NULL;
        }
        struct ListNode *temp = pHead;
        while(temp != slow) {
            temp = temp->next;
            slow = slow->next;
        }
        return temp;
    }
};

##关于快指针速度的解释
https://blog.csdn.net/xgjonathan/article/details/18034825

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值