环形链表#141

目标

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

进阶:
你能否不使用额外空间解决此题?

实现:

C :

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     struct ListNode *next;
 * };
 */

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

    while(f->next && f->next->next) {
        f = f->next->next;
        head = head->next;
        
        if(head == f) {
            return true;
        }
    }

    return false;
}

/*思路:长短步伐赶路,移动快的,遇上移动慢的必定有环。*/