LeetCode — Linked List Cycle II 解题报告

转载请注明:

原题如下:



题目解析:

     这道题目是“判断单链表是否有环,如果有环,求入环点,如果没有返回NULL”。

     首先我们需要判断是否有环,可以用经典的做法,设定两个指针,一个快指针,一个慢指针,快指针每次走两步,慢指针每次走一步,如果两个指针重合,则说明环存在。当环存在的时候,链表有一个性质,就是头结点到入环点和快慢指针碰撞点到入环点的距离相等。利用这个性质,我们就能很方便的求出入环点。只要从碰撞点和头结点一起走,知道两个相遇就是入环点。


题目代码:

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode *detectCycle(ListNode *head) {
        ListNode* result = NULL;
        if(head == NULL || head->next == NULL){
            return result;
        }
        
        ListNode* slow = head;
        ListNode* fast = head;
        while(fast != NULL && fast->next != NULL){
            slow = slow->next;
            fast = fast->next->next;
            if(slow == fast){
                break;
            }
        }
        
        //no cycle
        if(fast == NULL || fast->next == NULL){
            return result;
        }
        
        //exist cycle
        //the distance is equal from the intersection and head to 
        //cycle begins.
        slow = head;
        while(slow != fast){
            slow = slow->next;
            fast = fast->next;
        }
        
        result = slow;
        
        return result;
        
    }
};


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值