Leetcode160. 相交链表 -hot100-代码随想录-春招冲刺

题目:


代码(首刷看解析 2024年1月13日):

class Solution {
public:
    ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
        ListNode *A = headA, *B = headB;
        while (A != B) {
            A = A != nullptr ? A->next : headB;
            B = B != nullptr ? B->next : headA;
        }
        return A;
    }
};

        真给Krahet大佬跪了,这题以前做过,我用的和Krahet大佬一样的思路,我写的代码又臭又长还时间超时,大佬的代码几行解决。

代码(二刷看了解析 2024年3月4日)

        思路是对的,但是代码写的太烂了,把curA = curA->next;curB = curB->next;一起放在循环最后的话会出现各种各样的问题。

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
        if (headA == nullptr || headB == nullptr) return nullptr;
        ListNode* curA = headA;
        ListNode* curB = headB;
        while (curA != curB) {
            if (curA && curB && curA->next == nullptr && curB->next == nullptr) {
                return nullptr;
            }
            if (curA == nullptr) {
                curA = headB;
            } else curA = curA->next;
            if (curB == nullptr) {
                curB = headA;
            } else curB = curB->next;
        }
        return curA;
    }
};

       


代码(三刷看了解析 2024年4月12日)

class Solution {
public:
    ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
        ListNode* A = headA;
        ListNode* B = headB;
        while (A != B) {
            A = A == nullptr ? headB : A->next;
            B = B == nullptr ? headA : B->next;
        }
        return A;
    }
};

代码(四刷自解 2024年4月23日 8min)

class Solution {
public:
    ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
        // 双指针,直到相遇 or 都为空
        ListNode* curA = headA;
        ListNode* curB = headB;
        while (curA != curB) {
            curA = curA == nullptr ? headB : curA->next;
            curB = curB == nullptr ? headA : curB->next;
        }
        return curA;
    }
};

  • 9
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值