141-Linked List Cycle

来源:互联网 发布:java axis2 调用wsdl 编辑:程序博客网 时间:2024/06/03 19:26
题目

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

分析

快慢指针,当快指针追上慢指针,说明链表成环

实现
class Solution {public:    bool hasCycle(ListNode *head) {        if (head == NULL|| head->next == NULL)            return false;        ListNode *slow = head, *fast = head;        while (fast->next&&fast->next->next)        {            slow = slow->next;            fast = fast->next->next;            if (slow == fast)                return true;        }        return false;    }};