LeetCode | Intersection of Two Linked Lists

https://leetcode.com/problems/intersection-of-two-linked-lists/

将其中一条链表首尾相接,然后对另外一条链表进行环路检测。如果两个链表相交,那么另外一条链表就是带环链表,否则无环。问题转化为linked list cycle II了。

记得最后将链表复原。

C++

class Solution {
public:
    ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
        if (!headA || !headB) return NULL;
        
        ListNode *tailB = headB;
        while (tailB->next) tailB = tailB->next;
        tailB->next = headB;
        
        ListNode *ret = detect_cycle(headA);
        tailB->next = NULL;
        return ret;
    }
    
    ListNode *detect_cycle(ListNode *head) {
        bool is_cycle = false;
        ListNode *slow = head, *fast = head;
        while (fast && fast->next) {
            slow = slow->next;
            fast = fast->next->next;
            if (slow == fast) { is_cycle = true; break; }
        }
        
        if (!is_cycle) return NULL;
        ListNode *start = head;
        while (start != slow) {
            slow = slow->next;
            start = start->next;
        }
        return start;
    }
};
posted @ 2017-02-11 14:01  mioopoi  阅读(104)  评论(0编辑  收藏  举报