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

LeetCode Linked List Cycle II

时间:2014-06-22 23:59:58      阅读:244      评论:0      收藏:0      [点我收藏+]

标签:style   class   blog   code   ext   color   

/**
 * 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) {
        ListNode* fast = head;
        ListNode* slow = head;
        while (step(fast, 2) && step(slow, 1)) {
            if (fast == slow) break;
        }
        if (fast == NULL) {
            return NULL;
        }
        ListNode* fake_end = slow;
        
        ListNode* h2 = fake_end->next;
        ListNode* h1 = head;
        
        ListNode* cur1 = h1;
        ListNode* cur2 = h2;
        
        int len1 = 0, len2 = 0;
        
        while (cur1 != fake_end) len1++, cur1 = cur1->next;
        while (cur2 != fake_end) len2++, cur2 = cur2->next;
        
        if (len1 == len2) {
            len1 = len2 = 0;
        } else if (len1 > len2) {
            len1 = len1 - len2;
            len2 = 0;
        } else {
            len1 = 0;
            len2 = len2 - len1;
        }
        
        step(h1, len1);
        step(h2, len2);
        
        while (h2 != h1 && step(h1, 1) && step(h2, 1));
        
        return h1;
    }
    
    bool step(ListNode* &cur, int n) {
        while (cur != NULL && n > 0) {
            n--;
            cur = cur->next;
        }
        return n == 0;
    }
};

求链表环和Y型链表交点的结合。

LeetCode Linked List Cycle II,布布扣,bubuko.com

LeetCode Linked List Cycle II

标签:style   class   blog   code   ext   color   

原文地址:http://www.cnblogs.com/lailailai/p/3800013.html

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