Leetcode问题141超出时间限制

时间:2018-10-15 03:58:55

标签: c

这是我的代码,它适用于我的本地编译器。 但是在Leetcode上获得了“超过时间限制”。

我的想法是使每个节点指向头节点,然后 遍历,因此如果到达头节点意味着存在一个循环。

bool hasCycle(struct ListNode *head) {
    if (head == NULL)
        return false;

    struct ListNode *now;
    struct ListNode *pre;
    now = head;

    pre = now;
    now = now->next;
    pre->next = head;

    while(now != NULL){
        if (now == head){
            return true;
        }

        pre = now;
        now = now->next;
        pre->next = head;
    }

    return false;
}

1 个答案:

答案 0 :(得分:0)

循环链接列表有多种形式,您不能断定head是链接列表中的一项。

也许是这样

head -> a -> b -> c
        ^         |
        |         |
        -----------

您可以定义快速指针和慢速指针,以2为步长定义快速指针,以1为步长定义慢速指针。如果列表是一个循环,则fast最终将等于long。

bool hasCycle(struct ListNode* head) {
    if (head == NULL || head->next == NULL) {
        return false;
    }

    struct ListNode* fast;
    struct ListNode* slow;
    fast = head->next->next;
    slow = head->next;

    while (fast && fast->next) {
        if (fast == slow) {
        return true;
        }

        fast = fast->next->next;
        slow = slow->next;
    }

    return false;
}
相关问题