码迷,mamicode.com
首页 > 其他好文 > 详细

[LeetCode] Linked List Cycle 单链表中的环

时间:2014-12-02 14:56:30      阅读:177      评论:0      收藏:0      [点我收藏+]

标签:style   blog   io   color   使用   sp   for   on   div   

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

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

 

开始以为这道题只需要注意不使用额外空间即可,于是写了个时间复杂度为O(n^2)暴力搜索算法,如下:

 

/**
 * Dumped, Time Limit Exceeded
 */
class Solution {
public:
    bool hasCycle(ListNode *head) {
        if (!head || !head->next) return false;
        ListNode *pre = head;
        ListNode *cur = head->next;
        while (cur) {
            pre = head;
            while (cur->next != pre && pre != cur) {
                pre = pre->next;
            }
            if (cur->next == pre && pre != cur) return true;
            cur = cur->next;
        }
        return false;
    }
};

 

可是OJ还是不给通过,原因是Time Limit Exceeded,还是需要把时间复杂度缩小的O(n)才行,于是上网搜各位大神的方法,发现果然很神奇。只需要设两个指针,一个每次走一步的慢指针和一个每次走两步的快指针,如果链表里有环的话,两个指针最终肯定会相遇。实在是太巧妙了,要是我肯定想不出来。代码如下:

 

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

 

[LeetCode] Linked List Cycle 单链表中的环

标签:style   blog   io   color   使用   sp   for   on   div   

原文地址:http://www.cnblogs.com/grandyang/p/4137187.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!