题解 | #判断链表中是否有环#

判断链表中是否有环

https://www.nowcoder.com/practice/650474f313294468a4ded3ce0f7898b9

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
#include <cmath>
class Solution {
public:
    bool hasCycle(ListNode *head) {
        if (head == nullptr) {
            return false;
        }
        
        /* 如果不破坏链表的话,设置两个步长不同的指针,快的指针会把慢的套圈 */
        ListNode* slowPtr = head;
        ListNode* fastPtr = head->next;

        while (fastPtr != nullptr && fastPtr->next != nullptr) {
            if (fastPtr == slowPtr) {
                return true;
            }
            fastPtr = fastPtr->next->next;
            slowPtr = slowPtr->next;
        }
        return false;

    }
};

全部评论

相关推荐

05-27 14:57
西北大学 golang
强大的社畜在走神:27届真不用急,可以搞点项目、竞赛再沉淀沉淀,我大二的时候还在天天打游戏呢
投递华为等公司10个岗位
点赞 评论 收藏
分享
06-10 23:36
已编辑
首都经济贸易大学 C++
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务