141. linked list cycle
难度:Easy
刷题内容
原题连接
- https://leetcode.com/problems/linked-list-cycle/
-
内容描述
Given a linked list, determine if it has a cycle in it.
Follow up:
Can you solve it without using extra space?
���ⷽ��
˼· **- ʱ�临�Ӷ�: O(N)*- �ռ临�Ӷ�: O(1)***
������͵Ŀ���ָ内容描述�е����ã内容描述�ָ�룬ÿ��ѭ����һ����1����һ����2������ָ内容描述���л���
/**
* 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 == nullptr)
return false;
ListNode* l1 = head,*l2 = head ->next;
while(true)
{
if(l2 == nullptr || l2 ->next == nullptr)
return false;
if(l1 == l2)
return true;
l1 = l1 ->next;
l2 = l2 ->next ->next;
}
}
};