141.环形链表

4/16/2021 Leetcode

# 题目

https://leetcode-cn.com/problems/linked-list-cycle/

# 思路

快慢指针,慢指针slow每次走一步,快指针fast每次走两步,如果相遇就说明有环,如果fast或者fast->next为空说明没有环。

# 代码

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

    }
};
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27