美文网首页
141. Linked List Cycle

141. Linked List Cycle

作者: YellowLayne | 来源:发表于2017-06-21 17:23 被阅读0次

    1.描述

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

    Follow up:
    Can you solve it without using extra space?

    2.分析

    快慢指针,慢指针一次走一步,快指针一次走两步。
    如果快指针与慢指针相遇,则说明存在环。

    3.代码

    /**
     * Definition for singly-linked list.
     * struct ListNode {
     *     int val;
     *     struct ListNode *next;
     * };
     */
    bool hasCycle(struct ListNode *head) {
        if (NULL == head || NULL == head->next || NULL == head->next->next) return false;
        struct ListNode *fast = head->next->next;
        struct ListNode *slow = head;
        while (fast != slow) {
            if (NULL == fast->next || NULL == fast->next->next) return false;
            fast = fast->next->next;
            slow = slow->next;
        }
        return true;
    }
    

    相关文章

      网友评论

          本文标题:141. Linked List Cycle

          本文链接:https://www.haomeiwen.com/subject/weetcxtx.html