LeetCode NO.141 cpp(4.3)

标签:环形链表,双指针,快慢指针

在这里插入图片描述
在这里插入图片描述

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

在这里插入图片描述

发布了14 篇原创文章 · 获赞 0 · 访问量 147

猜你喜欢

转载自blog.csdn.net/weixin_45438011/article/details/104903243