Le migliori 150 intervisteFacile

Ciclo di elenchi collegati

Guida dettagliata e implementazione Python per il problema del "Ciclo di liste collegate".

Dichiarazione del problema

Facile

Dato head, l'inizio di una lista concatenata, determina se la lista concatenata contiene un ciclo.

C'è un ciclo in una lista concatenata se c'è qualche nodo nella lista che può essere raggiunto nuovamente seguendo continuamente il puntatore successivo. Internamente, pos viene utilizzato per denotare l'indice del nodo a cui è connesso il puntatore successivo di tail. Tieni presente che pos non viene passato come parametro.

Restituisce vero se è presente un ciclo nell'elenco collegato. Altrimenti restituisci false.

L'input viene fornito come un elenco di valori e un numero intero pos (l'indice a cui si collega la coda, -1 se nessun ciclo). Implementa una funzione hasCycle(head: list, pos: int) -> bool.

Vincoli
  • The number of nodes in the list is in the range [0, 10000]
  • -100000 <= Node.val <= 100000
  • pos is -1 or a valid index in the linked list

Esempi

Example 1
Input
[3,2,0,-4], 1
Output
True
Explanation

There is a cycle: the tail node (-4) connects back to the node at index 1 (value 2).

Example 2
Input
[1,2], 0
Output
True
Explanation

There is a cycle: the tail node (2) connects back to the node at index 0 (value 1).

Example 3
Input
[1], -1
Output
False
Explanation

There is no cycle in the list.

Need a Hint?
Prendi in considerazione l'utilizzo di strutture dati specifiche dell'elenco collegato come set o heap.
Edge Cases to Watch
  • Strutture di input vuote
  • Ingressi a elemento singolo
  • Grandi limiti numerici

Pronto a risolvere?

Open the problem in PyRun's browser-based Python editor. Your code runs fully offline — no server required.

Apri nell'editor
Found this breakdown helpful?

PyRun is built and maintained by an independent solo developer. If this helped your interview prep, consider buying a coffee!

Buy me a coffee

Risorse Python consigliate

Espandi le tue conoscenze con tutorial interattivi, foglietti illustrativi e confronti di codici correlati.