LeetCode141环形链表

给定一个链表,判断链表中是否有环。

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     struct ListNode *next;
 * };
 */
bool hasCycle(struct ListNode *head) {
    struct ListNode *fast, *slow;
    if(head == NULL || head -> next == NULL)
        return false;
    slow = head;
    fast = head -> next;
    while(slow != fast){
        if(fast == NULL || fast -> next == NULL)
            return false;
        slow = slow -> next;
        fast = fast -> next -> next;
    }
    return true;
}

猜你喜欢

转载自blog.csdn.net/a_learning_boy/article/details/84392384