1. 程式人生 > >141 Linked List Cycle 環形鏈表

141 Linked List Cycle 環形鏈表

list CP head light solution clas highlight lin nullptr

給定一個鏈表,判斷鏈表中否有環。
補充:
你是否可以不用額外空間解決此題?
詳見:https://leetcode.com/problems/linked-list-cycle/description/

/**
 * 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==nullptr)
        {
            return false;
        }
        ListNode *slow=head;
        ListNode *fast=head;
        while(fast&&fast->next)
        {
            slow=slow->next;
            fast=fast->next->next;
            if(slow==fast)
            {
                return true;
            }
        }
        return false;
    }
};

141 Linked List Cycle 環形鏈表