您的位置:首页 > 其它

LeetCode: linked list cycle I and II

2015-03-15 18:47 363 查看
Given a linked list, determine if it has a cycle in it.

Follow up:

Can you solve it without using extra space?

这道题非常常见,http://blog.csdn.net/hf81970/article/details/14169655 这篇文章讲的非常全面。分析简单明确。

代码:

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode *detectCycle(ListNode *head) {
       if(head == NULL || head->next == NULL)
            return NULL;
       ListNode* fast = head->next->next, * slow = head->next;
       ListNode* start = NULL;
       while(fast && slow)
       {
           if(fast == slow)
            {
                start = fast;
                break;
            }
            slow = slow->next;
            fast = fast->next;
            if(!fast)
                return NULL;
            fast = fast->next;
       }
       if(start == NULL)
            return NULL;
        ListNode * p1 = start, *p2 = head;
        while(p1 != p2)
        {
            p1 = p1->next;
            p2 = p2->next;
        }
        return p1;
    }
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: