LeetCode - Linked List Cycle

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

http://oj.leetcode.com/problems/linked-list-cycle/


Solution:

Very popular problem. Use two pointer, p1 move two steps every time and p2 move one step every time. If there is a cycle, p1 and p2 will meet together in the cycle.

https://github.com/starcroce/leetcode/blob/master/linked_list_cycle.cpp

// 68 ms for 16 cases
/**
 * 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) {
        // IMPORTANT: Please reset any member data you declared, as
        // the same Solution instance will be reused for each test case.
        ListNode *fast = head;
        ListNode *slow = head;
        while(fast != NULL && fast->next != NULL) {
            fast = fast->next->next;
            slow = slow->next;
            if(fast == slow) {
                return true;
            }
        }
        return false;
    }
};


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章