leetcode142 环形链表II

简介: leetcode142 环形链表II

环形链表


53303050ff6d489481456ab5a1d3e4a4.png7113231335ac43eea432a4aadbb069cb.png


双指针

环形链表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) {
        ListNode *dummy = new ListNode; 
        dummy->val = 0;  
        dummy->next = head;
        ListNode *fast , *slow;
        fast = dummy;
        slow = dummy;
        while(fast != NULL && fast->next != NULL)
        {
            slow = slow->next;
            fast = fast->next->next;
            if(slow == fast)
            {
                ListNode *indnx1 = fast;
                ListNode *indnx2 = dummy;
                while(indnx1 != indnx2)
                {
                    indnx1 = indnx1->next;
                    indnx2 = indnx2->next;
                }
                return indnx2;
            }
        }
        return NULL;
    }
};


二刷

/**
 * 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) {
        ListNode *right = head , *left = head;
        while(right != nullptr && right->next != nullptr)
        {
            right = right->next->next;
            left = left->next;
            if(right == left)
            {
                ListNode *indnx1 = head;
                ListNode *indnx2 = right;
                while(1)
                {   
                    if(indnx1 == indnx2) return indnx1;
                    indnx1 = indnx1->next;
                    indnx2 = indnx2->next;
                }
            }
        }
        return nullptr;
    }
};
相关文章
|
1月前
|
算法
LeetCode刷题---21.合并两个有序链表(双指针)
LeetCode刷题---21.合并两个有序链表(双指针)
|
1月前
|
算法
LeetCode刷题---19. 删除链表的倒数第 N 个结点(双指针-快慢指针)
LeetCode刷题---19. 删除链表的倒数第 N 个结点(双指针-快慢指针)
【移除链表元素】LeetCode第203题讲解
【移除链表元素】LeetCode第203题讲解
|
1月前
|
算法 测试技术
LeetCode刷题--- 430. 扁平化多级双向链表(深度优先搜索)
LeetCode刷题--- 430. 扁平化多级双向链表(深度优先搜索)
|
1月前
|
算法 安全 数据处理
LeetCode刷题---707. 设计链表(双向链表-带头尾双结点)
LeetCode刷题---707. 设计链表(双向链表-带头尾双结点)
|
11天前
【力扣】21. 合并两个有序链表
【力扣】21. 合并两个有序链表
|
1月前
|
存储 JavaScript
leetcode82. 删除排序链表中的重复元素 II
leetcode82. 删除排序链表中的重复元素 II
22 0
|
1月前
leetcode83. 删除排序链表中的重复元素
leetcode83. 删除排序链表中的重复元素
10 0
|
1月前
leetcode2807.在链表中插入最大公约数
leetcode2807.在链表中插入最大公约数
16 0
|
1月前
leetcode2487.从链表中移除节点
leetcode2487.从链表中移除节点
20 1