easy141. Linked List Cycle

Posted Sherry_Yang

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了easy141. Linked List Cycle相关的知识,希望对你有一定的参考价值。

非常简单的题:判断链表有没有环(用快慢指针)

/**
 * 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;
            slow = slow->next;
            if (fast == NULL)
                return false;
            if (fast == slow)
                return true;
        }
        return false;
    }
};

 

以上是关于easy141. Linked List Cycle的主要内容,如果未能解决你的问题,请参考以下文章