欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

LeetCode141. 环形链表&&142. 环形链表 II

程序员文章站 2024-03-08 18:39:22
...

141. 环形链表

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    //快慢指针
    bool hasCycle(ListNode *head) {
        if(!head || head->next == nullptr) return false;
        ListNode *fast = head;   
        ListNode *slow = head;
        while(fast && fast->next) {
            fast = fast->next->next;
            slow = slow->next;
            if(fast == slow) return true;
        }
        return false;
    }
};

142. 环形链表 IILeetCode141. 环形链表&&142. 环形链表 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;
        ListNode *slow = head;

        while(fast && fast->next) {
            fast = fast->next->next;
            slow = slow->next;
            if(fast == slow) {
                ListNode *temp = head;
                while(fast != temp) {
                    fast = fast->next;
                    temp = temp->next;
                }
                return temp;
            }
        }
        return nullptr;
    }
};
相关标签: LeetCode刷题