#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;
}
}
};