题目:
Given a linked list, determine if it has a cycle in it.
题意:
判断一个链表是否存在环。
思路:
使用快慢两个指针,一个一次走一步,一个一次走两步。
代码如下:
/**
* 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 == NULL || head->next == NULL || head->next->next == NULL)return false;
ListNode* first = head, *second = head->next;
while(first != second && second != NULL && second->next != NULL) {
first = first->next;
second = second->next->next;
}
return (first == second);
}
};