leetcode 141 142. Linked List Cycle

Posted StrongYaYa

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了leetcode 141 142. Linked List Cycle相关的知识,希望对你有一定的参考价值。

题目描述:

不用辅助空间判断,链表中是否有环

/**
 * 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) {
        if(head == NULL)
            return false;
        ListNode *first = head;
        ListNode *Second = head;
        while(Second->next != NULL){
            
            first = first->next;
            Second = Second->next->next;
            if(Second == NULL)
                return false;
            if(Second == first)
                return true;
        }
        return false;
    }
};

142  找到环开始的结点

 

第一次相遇时slow走过的距离:a+b,fast走过的距离:a+b+c+b。

因为fast的速度是slow的两倍,所以fast走的距离是slow的两倍,有 2(a+b) = a+b+c+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) {
        if(head == NULL)
            return NULL;
        ListNode *first = head;
        ListNode *second = head;
        bool flag = true;
        while(second->next != NULL){
            first = first->next;
            second = second->next->next;
            if(second == NULL)
                return NULL;
            if(first == second){
                flag = false;
                break;
            }
        }
        if(flag == true)
            return NULL;
        first = head;
        while(first != second){
            first = first->next;
            second = second->next;
        }
        return first;
        
    }
};

 

以上是关于leetcode 141 142. Linked List Cycle的主要内容,如果未能解决你的问题,请参考以下文章

leetcode 141 142. Linked List Cycle

LeetCode 141, 142. Linked List Cycle I+II

leetcode 141 142 Linked List Cycle I/II

算法分析如何理解快慢指针?判断linked list中是否有环找到环的起始节点位置。以Leetcode 141. Linked List Cycle, 142. Linked List Cycl(代码

LeetCode 142. Linked List Cycle II

leetcode-142. Linked List Cycle II