Day17: [LeetCode中等] 142. 环形链表 II

Day17: [LeetCode中等] 142. 环形链表 II

题源:

来自leetcode题库:

https://leetcode-cn.com/problems/linked-list-cycle-ii/

思路:

这道题如果忽视掉不用额外空间这个条件的话,就是一道中等题。但是加上这个额外条件,当做一道困难难度的题没问题。思路就是三步走,具体看代码吧,或者是题解。这题没什么代码难度,主要就是得脑子转过这个弯,算一道智力题吧。

代码:

dirty code凑合看吧

/**
 * 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) return head;
        auto slow=head,fast=head;
        int count=0,Len=0;
        //第一步,用快慢指针确定有是否环,同时确定环的长度
        while(1){
            Len++;
            if(fast==NULL||fast->next==NULL) return NULL;
            slow=slow->next;
            fast=fast->next->next;
            if(slow==fast) break;
        }
        cout<<Len;
        //第二步,先让slow走环的长度
        slow=fast=head;
        for(int i=0;i<Len;i++){
            slow=slow->next;
        }
         //第三步,两个指针一起走,相遇时便是环的起始点
        while(slow!=fast){
            slow=slow->next;
            fast=fast->next;
        }
        return slow;
    }
};
发布了49 篇原创文章 · 获赞 13 · 访问量 547

猜你喜欢

转载自blog.csdn.net/qq2215459786/article/details/103140846