美文网首页
141. Linked List Cycle

141. Linked List Cycle

作者: SilentDawn | 来源:发表于2018-06-28 16:03 被阅读0次

    Problem

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

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

    Code

    /**
     * Definition for singly-linked list.
     * struct ListNode {
     *     int val;
     *     ListNode *next;
     *     ListNode(int x) : val(x), next(NULL) {}
     * };
     */
    static int var = [](){
        std::ios::sync_with_stdio(false);
        cin.tie(NULL);
        return 0;
    }();
    class Solution {
    public:
        bool hasCycle(ListNode *head) {
            if(head==NULL)
                return false;
            ListNode* fast = head;
            ListNode* slow = head;
            while(fast->next!=NULL && fast->next->next!=NULL){
                fast=fast->next->next;
                slow=slow->next;
                if(slow==fast)
                    return true;
            }
            return false;
        }
    };
    

    Result

    141. Linked List Cycle.png

    相关文章

      网友评论

          本文标题:141. Linked List Cycle

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