两道链表的简单数学题

两道链表的简单数学题

1.环形链表

LC142环形链表II
配图证明:双指针的一个数学题
在这里插入图片描述

/**
 * 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 == nullptr || head->next == nullptr) return nullptr;
        ListNode* fast=head->next->next;
        ListNode* slow=head->next;
        while(slow!=fast){
            if(fast==nullptr || fast->next==nullptr) return nullptr;
            fast=fast->next->next;
            slow=slow->next;

        }
        fast=head;
        while(fast!=slow) {
            fast=fast->next;
            slow=slow->next;
        }
        return slow;
    }
};

这个代码还是挺容易错的。
主要是这俩If语句
fast和slow的初始化。
当然用head初始化fast和slow也行,就是要把while改成do-while;

2.相交链表

LC160相交链表
证明:

在这里插入图片描述
代码:

/**
 * 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) {
         ListNode *h1=headA, *h2=headB;
        while(h1!=h2)
        {
            h1=h1==nullptr? headB: h1->next;
            h2=h2==nullptr? headA: h2->next;
        }
        return h1;
        
    }
};

?:这个三目运算符用的很不错。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值