Saturday, July 9, 2016

Linked List Cycle

Given a linked list, determine if it has a cycle in it.

Solution:

/**
 * 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 false;
        ListNode *speedy = head;
        while (head != NULL && speedy != NULL) {
            head = head -> next;
            speedy = speedy -> next ? speedy -> next -> next : NULL;
            if (head == speedy)
                return true;
        }
        return false;
    }
};

No comments:

Post a Comment