---
# System prepended metadata

title: '[LeetCode 141. Linked List Cycle]'
tags: [Leetcode]

---

# [LeetCode 141. Linked List Cycle]
###### tags: `Leetcode`
* 題目
    Given head, the head of a linked list, determine if the linked list has a cycle in it.

    There is a cycle in a linked list if there is some node in the list that can be reached again by continuously following the next pointer. Internally, pos is used to denote the index of the node that tail's next pointer is connected to. Note that pos is not passed as a parameter.

    Return true if there is a cycle in the linked list. Otherwise, return false.
* 解法
    *   一開始的想法就是從頭開始往下走，經過的地方就存在hashset，然後後面的再看看有沒有經過，這樣的缺點就是會隨著data的增加，而增加記憶體使用量。
    *   第二種解法是用two pointer，一個一次走一步，一個走兩步，如果有cycle的話，他們就一定會相遇(p==q)

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