141. Linked List Cycle&142. Linked List Cycle II

来源:互联网 发布:王者荣耀开黑连麦软件 编辑:程序博客网 时间:2024/05/09 09:47

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

class Solution {public:    bool hasCycle(ListNode *head) {                if(head==NULL) return 0;                ListNode *fast=head;        ListNode *slow=head;                while(fast->next&&fast->next->next){                        fast=fast->next->next;            slow=slow->next;            if(fast==slow) return 1;                    }                return 0;            }};

值得注意的是一开始会疑惑为什么while的check条件要检查fast->next和fast->next->next,而不是检查slow,后来想通了,因为fast走得比slow快,如果链表没有循环的话,fast会更快走到NULL的地方。因此需要进行检查。


Given a linked list, return the node where the cycle begins. If there is no cycle, returnnull.

这题有个链接讲得很好:http://blog.csdn.net/u014248312/article/details/51712554

class Solution {public:    ListNode *detectCycle(ListNode *head) {                if(head==NULL) return NULL;                ListNode *fast=head;        ListNode *slow=head;                while(fast->next&&fast->next->next){            fast=fast->next->next;            slow=slow->next;            if(fast==slow){                slow=head;                while(fast!=slow){                    slow=slow->next;                    fast=fast->next;                }                                return fast;            }                    }                return NULL;            }};


0 0
原创粉丝点击