Linked List Cycle

2017/12/16 posted in  leetcode

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==NULL||head->next==NULL) {
            return 0;
        }
        ListNode *slow = head;
        ListNode *fast = head;
        while (fast->next&&fast->next->next) {
            fast = fast->next->next;
            slow = slow->next;
            if (fast==slow) {
                return 1;
            }
        }
        return 0;
    }
};