Introducción

1

¿Ya tomaste el Curso Avanzado de Algoritmos: Patrones de Arrays y Strings?

Lista Enlazada

2

Estructura de datos: Lista Enlazada

3

Programando listas enlazadas con Java

4

Cómo Invertir una Lista Enlazada

5

Odd Even Linked List: análisis del problema

6

Solución de Odd Even Linked List

7

Playground: Odd Even Liked List

8

Programando Odd Even Linked List con C++

9

Linked List Cycle: análisis del problema

10

Solución de Linked List Cycle

11

Playground: Linked List Cycle

12

Programando Linked List Cycle con Python

13

Palindrome Linked List: análisis del problema

14

Solución de Palindrome Linked List

15

Playground: Palindrome Linked List

16

Programando Palindrome Linked List con Java

17

Reorder List: análisis del problema

18

Solución de Reorder List

19

Programando Reorder List con JavaScript

20

Playground: Reorder List Without Repeated Values

21

Reto: LRU Caché

22

Ejercicios Prácticos con Listas Enlazadas y Historial de Navegador

23

Operaciones con Listas Enlazadas: Suma, Intercambio y Navegador

Pilas y colas

24

Estructura de datos: Pilas y Colas

25

Paréntesis Válido: análisis del problema

26

Solución de Paréntesis Válido

27

Playground: Paréntesis Válido

28

Programando Paréntesis Válido con C++

29

Comparación de Cadenas con Backspaces

Colas de prioridad

30

Estructura de datos: Colas de Prioridad

31

K Closest Points to Origin: análisis del problema

32

Solución de K Closest Points to Origin

33

Playground: K Closest Points to Origin

34

Programando K Closest Points to Origin con Python

35

Reorganize String: análisis del problema

36

Solución de Reorganize String

37

Playground: Reorganize String

38

Programando Reorganize String con Python

39

Colas de Prioridad: Ejercicios Prácticos y Soluciones

40

Colas de Prioridad y Gestión de Eventos

Próximos pasos

41

Toma el Curso Avanzado de Algoritmos: Grafos y Árboles

No tienes acceso a esta clase

¡Continúa aprendiendo! Únete y comienza a potenciar tu carrera

Playground: Linked List Cycle

11/41

Aportes 10

Preguntas 0

Ordenar por:

¿Quieres ver más aportes, preguntas y respuestas de la comunidad?

My Solution!! ![](https://static.platzi.com/media/user_upload/image-817abd6c-816b-42dc-a36f-61195436b184.jpg)
Yo agregué una propiedad booleana a la clase Nodo, para saber si cada nodo ya ha sido visitado previamente. Aquí mi solución:class Nodo:   def \_\_init\_\_(self, x):      self.valor = x      self.siguiente = None      self.visitado = False def hasCycle(cabeza: Nodo) -> bool:   nodo = cabeza   while nodo is not None:      if not nodo.visitado:         nodo.visitado = True         nodo = nodo.siguiente      else:         return True    return False nodo1 = Nodo(1)nodo2 = Nodo(2)nodo3 = Nodo(3)nodo4 = Nodo(4)nodo1.siguiente = nodo2nodo2.siguiente = nodo3nodo3.siguiente = nodo4nodo4.siguiente = nodo2 response = hasCycle(nodo1)print(response) ```js class Nodo: def __init__(self, x): self.valor = x self.siguiente = None self.visitado = False def hasCycle(cabeza: Nodo) -> bool: nodo = cabeza while nodo is not None: if not nodo.visitado: nodo.visitado = True nodo = nodo.siguiente else: return True return False nodo1 = Nodo(1) nodo2 = Nodo(2) nodo3 = Nodo(3) nodo4 = Nodo(4) nodo1.siguiente = nodo2 nodo2.siguiente = nodo3 nodo3.siguiente = nodo4 nodo4.siguiente = nodo2 response = hasCycle(nodo1) print(response) ```
My COde @Here \[Bellow ] \n\n\n ```js class Nodo: def __init__(self, x): self.valor = x self.siguiente = None def hasCycle(cabeza: Nodo) -> bool: # Tu código aquí 👇...... if not cabeza : return False slow = fast = cabeza while ( fast is not None and fast.siguiente is not None ) : slow = slow.siguiente fast = fast.siguiente.siguiente if ( slow == fast ) : return True return False ```class Nodo: def \_\_init\_\_(self, x): self.valor = x self.siguiente = None def hasCycle(cabeza: Nodo) -> bool: # Tu código aquí 👇...... if not cabeza : return False slow = fast = cabeza while ( fast is not None and fast.siguiente is not None ) : slow = slow.siguiente fast = fast.siguiente.siguiente if ( slow == fast ) : return True return False
Comparto mi solución: ``` def hasCycle(self, head: Optional\[ListNode]) -> bool: if not head: return False slow = head fast = head while fast is not None and fast.next is not None: slow = slow.next fast = fast.next.next if slow == fast: return True return False ```

Siguiendo lo que dijo la profe:

.

aqui dejo mi solución, en esta oportunidad me pareció interesante utilizar el warus operator para hacer la asiganción de los apuntadores en la misma validación del while. ```python def hasCycle(cabeza: Nodo) -> bool: turtle = cabeza rabbit = cabeza while (turtle := turtle.siguiente) and rabbit.siguiente and (rabbit := rabbit.siguiente.siguiente): if turtle == rabbit: return True return False ```
aquí dejo mi solución, utilicé el walrus operator para realizar las asignaciones de los apuntadores durante la validación del while. ```python def hasCycle(cabeza: Nodo) -> bool: turtle = cabeza rabbit = cabeza while (turtle := turtle.siguiente) and rabbit.siguiente and (rabbit := rabbit.siguiente.siguiente): if turtle == rabbit: return True return False ```
Como desarrollador de js, hoy aprendí que los if de Python se ejecutan al mismo tiempo en lugar de izquierda a derecha. Y que Python no tiene optional chaining en los objetos 💀 ![](https://static.platzi.com/media/user_upload/image-23ab8995-b1a6-4831-8cb9-5ae35393aee3.jpg)

Mi solución fue si la cola (tail) es igual al Nodo que se esta iterando en el loop detener el ciclo, esta es mi solución en Java .

package org.example.circularloop;

public class LinkedListCircular {

    static Node head, tail;

    static class Node {
        int data;
        Node next;

        public Node(int data) {
            this.data = data;
            this.next = null;
        }
    }

    void push (int data) {
        Node currentNode = new Node(data);

        if (tail == null) {
            tail = currentNode;
            head = currentNode;
        }

        currentNode.next = head;
        head = currentNode;

        tail.next = head;
    }

    void print () {
        Node iteration = head;
        while (true) {
            System.out.print(iteration.data + " ");

            if (hasCycle() && iteration.equals(tail)) {
                break;
            }

            iteration = iteration.next;
        }

        System.out.println();
    }

    private boolean hasCycle () {
        return tail != null && tail.next != null;
    }

    public static void main(String[] args) {
        LinkedListCircular circular = new LinkedListCircular();

        circular.push(1);
        circular.push( 2);
        circular.push(3);
        circular.push(4);

        circular.print();
    }

}


<code> 

Para mi solución cree una variable estática longitud, para saber la cantidad de nodos agregados a la lista enlazada:

class Nodo:
   longitud = 0
   def __init__(self, x):
      self.valor = x
      self.siguiente = None
      Nodo.longitud += 1

def hasCycle(cabeza: Nodo) -> bool:
   actual = cabeza
   for i in range (cabeza.longitud):
      if (actual.siguiente == None):
            return False
      actual = actual.siguiente
   return True
undefined