題目:
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);
}
};