Linked List Cycle

Problem

Given head, the head of a linked list, determine if the linked list has a cycle in it.

There is a cycle in a linked list if there is some node in the list that can be reached again by continuously following the next pointer. Internally, pos is used to denote the index of the node that tail's next pointer is connected to. Note that pos is not passed as a parameter.

Return true if there is a cycle in the linked list. Otherwise, return false.

Example 1:

Linked List Cycle_第1张图片

Input: head = [3,2,0,-4], pos = 1
Output: true
Explanation: There is a cycle in the linked list, where the tail connects to the 1st node (0-indexed).

Intuition

This problem involves detecting a cycle in a linked list. We can use the "two-pointer" approach, where two pointers traverse the linked list at different speeds. If there is a cycle, the faster pointer will eventually catch up to the slower one.

Approach

Initialize two pointers, slow and fast, to the head of the linked list.
Traverse the linked list using the following conditions:
Move the slow pointer one step at a time.
Move the fast pointer two steps at a time.
If there is a cycle, the fast pointer will eventually catch up to the slow pointer.
If the fast pointer ever reaches the end of the linked list (i.e., it becomes None), return False (indicating no cycle).
If the fast pointer catches up to the slow pointer, return True (indicating the presence of a cycle).

Complexity

  • Time complexity:

The time complexity is O(n), where n is the number of nodes in the linked list. The pointers traverse the linked list at different speeds, but in the worst case, the fast pointer may need to traverse the entire list before detecting a cycle.

  • Space complexity:

The space complexity is O(1) since the solution only uses a constant amount of extra space for the two pointers.

Code

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    def hasCycle(self, head: Optional[ListNode]) -> bool:
        slow = fast = head

        while fast and fast.next:
            slow = slow.next
            fast = fast.next.next
            if slow == fast:
                return True
        
        return False

你可能感兴趣的:(leetcode算法学习,算法)