判断是否为环形链表

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

为了表示给定链表中的环,我们使用整数 pos 来表示链表尾连接到链表中的位置(索引从 0 开始)。 如果 pos 是 -1,则在该链表中没有环。

可以用快慢指针的方法来解决该问题

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

猜你喜欢

转载自www.cnblogs.com/xingmuxin/p/11271630.html