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 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.
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.
Example 3:
Input: head = [1], pos = -1
Output: false
Explanation: There is no cycle in the linked list.
pos
就好,但是你當然拿不到這個變數。linked list
裡面有cycle
。null
的時候不能再跑向下一個。
/**
* 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;
}
};
LeetCode
C++