Leetcode142. 环形链表 II

文章目录

  • 题目
  • 代码(首刷看解析)
  • 代码(7.30 二刷自解)
  • 代码(8.8 三刷自解)

题目

Leetcode142. 环形链表 II_第1张图片
142. 环形链表 II

代码(首刷看解析)

Leetcode142. 环形链表 II_第2张图片
Leetcode142. 环形链表 II_第3张图片

class Solution {
public:
    ListNode *detectCycle(ListNode *head) {
        auto fast = head, slow = head;
        while(fast && fast->next) {
            slow = slow->next;
            fast = fast->next->next;
            if(slow == fast)
                break;
        }
        if(!fast || !fast->next)
            return nullptr;
        slow = head;
        while(slow != fast) {
            slow = slow->next;
            fast = fast->next;
        }
        return slow;
    }   
};

代码(7.30 二刷自解)

class Solution {
public:
    ListNode *detectCycle(ListNode *head) {
        auto fast = head;
        auto slow = head;
        if(!fast || !fast->next)
            return nullptr;
        do {
            if(!fast || !fast->next)
                return nullptr;
            fast = fast->next->next;
            slow = slow->next;
        }while(fast != slow);
        slow = head;
        while(slow != fast) {
            slow = slow->next;
            fast = fast->next;
        }
        return slow;
    }
};

代码(8.8 三刷自解)

class Solution {
public:
    ListNode* EntryNodeOfLoop(ListNode* pHead) {
        auto fast = pHead, slow = pHead;
        while(fast && fast->next) {
            fast = fast->next->next;
            slow = slow->next;
            if(fast == slow)
                break;
        }
        if(!fast || !fast->next)
            return nullptr;
        slow = pHead;
        while(fast != slow) {
            fast = fast->next;
            slow = slow->next;
        }
        return fast;
    }
};

GO

func detectCycle(head *ListNode) *ListNode {
    fast, slow := head, head
    for fast != nil && fast.Next != nil {
        fast = fast.Next.Next
        slow = slow.Next
        if fast == slow {
            break
        }
    }
    if fast == nil || fast.Next == nil {
        return nil
    }
    slow = head
    for fast != slow {
        slow = slow.Next
        fast = fast.Next
    }
    return fast
}

你可能感兴趣的:(Leetcode专栏,链表,leetcode,数据结构)