LeetCode--Linked List Cycle(C++)

题目描述: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)
            return false;

        ListNode* fast=head;
        ListNode* slow=head;

        while(fast->next!=NULL)
        {
            fast=fast->next->next;
            if(fast==NULL)
            {
                return false;
            }

            slow=slow->next;
            if(slow==fast)
            {
                return true;
            }
        }

        return false;
    }
};

猜你喜欢

转载自blog.csdn.net/cherrydreamsover/article/details/81393309