141. Vinculado Lista Ciclo *

141. Vinculado Lista Ciclo *

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

título Descripción

Dada una lista enlazada, determinar si tiene un ciclo en el mismo.

Para representar un ciclo en la lista enlazada dado, utilizamos un número entero posque representa la posición (0-indexada) en la lista enlazada, donde se conecta la cola a. Si poses -1, entonces no hay ningún ciclo en la lista enlazada.

Ejemplo 1:

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

Ejemplo 2:

Input: head = [1,2], pos = 0
Output: true
Explanation: There is a cycle in the linked list, where tail connects to the first node.

Ejemplo 3:

Input: head = [1], pos = -1
Output: false
Explanation: There is no cycle in the linked list.

Seguimiento:

Se puede resolver usando la ( 1 ) O (1) (es decir, constante) de memoria?

Implementación en C ++ 1

Usando el puntero para determinar si la velocidad del anillo. El primero fue escrito durante la inicialización, el puntero de velocidad no apuntan al mismo nodo.

Además, 142. Ciclo II ** la lista enlazada Este problema requiere encontrar el nodo de inicio del anillo.

class Solution {
public:
    bool hasCycle(ListNode *head) {
        if (!head || !head->next) return false;
        ListNode *slow = head, *fast = head->next;
        while (fast && fast->next && slow != fast) {
            slow = slow->next;
            fast = fast->next->next;
        }
        return slow == fast;
    }
};

2 en C ++

Tal enfoque es el punto inicial para la misma velocidad del puntero nodo.

class Solution {
public:
    bool hasCycle(ListNode *head) {
        if (!head || !head->next)
            return false;

        ListNode *slow = head, *fast = head;
        while (fast && fast->next) {
            slow = slow->next;
            fast = fast->next->next;
            if (fast == slow)
                return true;
        }
        return false;
    }
};
Publicados 455 artículos originales · ganado elogios 8 · Vistas a 20000 +

Supongo que te gusta

Origin blog.csdn.net/Eric_1993/article/details/104959995
Recomendado
Clasificación