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;
    }
};

转载于:https://www.cnblogs.com/ilovezyg/p/6389098.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值