[C语言][LeetCode][141]Linked List Cycle

题目

Linked List Cycle
Given a linked list, determine if it has a cycle in it.

Follow up:
Can you solve it without using extra space?

标签

Linked List、Two Pointers

难度

中等

分析

题目意思是判断链表是否会回环。这里的解法是利用快慢指针,快指针每次走两步,慢指针每次走一步,如果快慢指针相遇,说明有回环。

C代码实现

bool hasCycle(struct ListNode *head)
{
    struct ListNode *fast, *slow;

    fast = head;
    slow = head;

    while(fast && fast->next)
    {
        fast = fast->next->next;
        slow = slow->next;

        if(fast == slow)
            return true;
    }

    return false;
}

你可能感兴趣的:(LeetCode,C语言)