[leetcode 141] Linked List Cycle

来源:互联网 发布:剑指offer c语言 编辑:程序博客网 时间:2024/05/04 16:11

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


1 0
原创粉丝点击