LeetCode题解——Linked List Cycle

来源:互联网 发布:iphone与mac传照片 编辑:程序博客网 时间:2024/06/05 21:07

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:    //想法:用两个指针,一个慢指针,一个快指针,当慢指针追上快指针时,那么有cycle    //特殊输入:空链表,两个节点的环形链表,多个节点的环形链表,普通链表    bool hasCycle(ListNode *head) {        if(!head) return false;        ListNode * fast = head;        ListNode * slow = head;        while(fast && fast->next){            fast = fast->next->next;            slow = slow->next;            if(fast==slow) return true;        }        return false;    }};


0 0