LeetCode 141 Linked List Cycle和142 Linked List Cycle II

题目

141 Linked List Cycle
Given a linked list, determine if it has a cycle in it.
Follow up:
Can you solve it without using extra space?

142 Linked List Cycle II
Given a linked list, return the node where the cycle begins. If there is no cycle, return null.
Note: Do not modify the linked list.
Follow up:
Can you solve it without using extra space?

解法

141、给一个链表,判断它是否存在环
一个快指针fast和一个慢指针slow,两个指针都从head开始走,快指针每次走两步,慢指针每次走一步,如果两者相遇,说明有环,并且此时fast超了slow一圈,返回true,否则没有环。
如果存在环,fast先进入,在slow进入之后,fast与slow每次循环都靠近1,所以一定会相遇。

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    bool hasCycle(ListNode *head) {
        ListNode* fast = head;
        ListNode* slow = head;
        while(fast !=NULL && fast->next!=NULL) {
            fast = fast->next->next;
            slow = slow->next;
            if (fast == slow)
                return true;
        }
        return false;
    }
};

142、给一个链表,如果它存在环,请返回环的起点,否则,返回NULL
快慢指针相遇后,慢指针重新指向head,然后fast和slow每次都走一步,当两者再次相遇时即为环的起点。
这里用一张网上找到的示意图来解释。图中仅列出了头结点、环起点、相遇结点。
假设快慢指针相遇与z点,则fast走过的路线为a+b+c+b,slow走过的路线为a+b,因为fast的速度是slow的两倍。所以a+b+c+b = 2*(a+b),化简可以得到a=c。

这里写图片描述

/**
 * 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* fast = head;
        ListNode* slow = head;
        bool isCycle = false;
        while(fast != NULL && fast->next != NULL) {
            fast = fast->next->next;
            slow = slow->next;
            if (fast == slow) {
                isCycle = true;
                break;
            }
        }
        if(!isCycle)
            return NULL;
        slow = head;
        while(fast != slow) {
            fast = fast->next;
            slow = slow->next;
        }
        return slow;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值