首页 > 其他 > 详细

leetcode || 141、Linked List Cycle

时间:2015-05-04 12:03:09      阅读:235      评论:0      收藏:0      [点我收藏+]

problem:

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

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

Hide Tags
 Linked List Two Pointers

thinking:

(1)如果可以开设额外的空间,使用unordered_set存储遍历过的结点,出现重复时即为存在环形结构

(2)如果不适用额外的空间,及空间复杂度为O(1),这里使用快、慢双指针。慢指针每次走一步,快指针每次走两步。

如果存在环形结构,两个指针总会相遇。

(3)终止条件也要注意:

fast!=NULL && fast->next!=NULL

防止出现fast->NULL->next

code:

/**
 * 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) {
          ListNode *fast,*slow;
         if(head==NULL) return false;
         slow=head;
         fast=head->next;
         while(fast!=NULL && fast->next!=NULL)
         {
             if(slow==fast) return true;
             slow=slow->next;
             fast=fast->next->next;
         }
         return false;
    }
};


leetcode || 141、Linked List Cycle

原文:http://blog.csdn.net/hustyangju/article/details/45477063

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!