leetcode141题。
Given a linked list, determine if it has a cycle in it.
Follow up:
Can you solve it without using extra space?
/**
* 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 * fast, * slow;
fast = slow = head;
while (fast && fast->next)
{
slow = slow->next;
fast = fast->next->next;
if (slow == fast)
return true;
}
return false;
}
};
题目有点读不懂意思,还特意去百度了一下,才看懂。使用2个指针,一个一次移动一步,一个一次移动两步,如果链表中存在环,则2个指针会出现相等的情况。循环条件的第二个条件是为了防止fast->next是null的情况下再->next。