Level 1 (day 4)

第一题

题目链接:https://leetcode.cn/problems/middle-of-the-linked-list/

个人题解:双指针,快指针走到尾,慢指针就走到中间了

代码:

class Solution {
public:
    ListNode* middleNode(ListNode* head) {
        auto f=head,s=head;
        while(f && f->next){
            s=s->next;// 走一步
            f=f->next->next;// 走两步
        }
        return s;
    }
};

第二题

题目链接:https://leetcode.cn/problems/linked-list-cycle-ii/

个人题解:双指针

代码:


class Solution {
public:
    ListNode *detectCycle(ListNode *head) {
        auto slow=head,fast=head;
        while(fast){
            slow=slow->next;
            if(!fast->next) return NULL;
            fast=fast->next->next;
            if(fast==slow) {
                auto ptr=head;
                while(ptr!=slow) {
                    ptr=ptr->next;
                    slow=slow->next;
                }
                return ptr;
            }
        }
        return NULL;
    }
};
posted @ 2022-06-26 22:47  黑VS白-清墨  阅读(22)  评论(0)    收藏  举报