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

判断链表中是否有环

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

少儿编程罢了

/**
 * 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) {

        short num = 1;
        while(head != nullptr) {
            head = head->next;
            // 计算链表长度
            num++;
            if (num > 10000) {
                break;
            }
        }

        if (num > 10000) {
            return true;
        } else {
            return false;
        }
    }
};

全部评论
兄弟们 实测8030是上限 /** * 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) { short num = 1; while(head != nullptr) { head = head->next; // 计算链表长度 num++; if (num > 8030) { return true; } } return false; } };
点赞 回复 分享
发布于 2025-02-25 21:41 安徽

相关推荐

2025-12-15 12:50
河北工程大学
sta666:我也是这个国际商业化的,三天,一天一面,就通过了,不过我是后端实习生,好好面感觉能过。
点赞 评论 收藏
分享
评论
1
收藏
分享

创作者周榜

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