# 【LeetCode】 141. Linked List Cycle ## Description > Given a linked list, determine if it has a cycle in it. > To represent a cycle in the given linked list, we use an integer pos which represents the position (0-indexed) in the linked list where tail connects to. If pos is -1, then there is no cycle in the linked list. > 給一linked list,判斷裡面有沒有cycle。 > 我們用一個整數pos去代表linked list的尾巴指回linked list前面的哪個位置,如果pos為-1,代表裡面沒有cycle。 ## Example: ``` Example 1: Input: head = [3,2,0,-4], pos = 1 Output: true Explanation: There is a cycle in the linked list, where tail connects to the second node. ``` ![](https://i.imgur.com/vil8Qw1.png) ``` Example 2: Input: head = [1,2], pos = 0 Output: true Explanation: There is a cycle in the linked list, where tail connects to the first node. ``` ![](https://i.imgur.com/1eKtcCv.png) ``` Example 3: Input: head = [1], pos = -1 Output: false Explanation: There is no cycle in the linked list. ``` ![](https://i.imgur.com/OE9vBnU.png) ## Solution * 你可能覺得去判斷`pos`就好,但是你當然拿不到這個變數。 * 去用兩個點指向頭,一個一次走一步,一個一次走兩步。如果兩個走到同一個點,代表`linked list`裡面有`cycle`。 * 需要小心指到`null`的時候不能再跑向下一個。 ### Code ```C++=1 /** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: bool hasCycle(ListNode *head) { if(!head)return false; ListNode* one=head->next; ListNode* two=head->next; if(!one)return false; two = two->next; if(!two)return false; for(;one&&two;one=one->next,two=two->next) { two=two->next; if(!two)return false; if(one==two)return true; } return false; } }; ``` ###### tags: `LeetCode` `C++`