English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
En este ejemplo, aprenderemos a detectar si existe un bucle en LinkedList de Java.
Para entender este ejemplo, debes conocer lo siguienteProgramación JavaTema:
class LinkedList { //Crear el objeto de la clase Node //Representa la cabeza de la lista Node head; //Clase interna estática static class Node { int value; //Conectar cada nodo al siguiente nodo Node next; Node(int d) { value = d; next = null; } } //Revisar si existe un bucle public boolean checkLoop() { //Crear dos referencias en el principio de LinkedList Node first = head; Node second = head; while (first != null && first.next != null) { //Mover la primera referencia2nodo first = first.next.next; //Mover la segunda referencia1nodo second = second.next; //Si dos referencias son iguales (encuentran) if (first == second) { return true; } } return false; } public static void main(String[] args) { //Crear el objeto LinkedList LinkedList linkedList = new LinkedList(); //Asignar valores a cada nodo de la lista enlazada linkedList.head = new Node(1); Node second = new Node(2); Node third = new Node(3); Node fourth = new Node(4); //Conectar cada nodo de la lista enlazada al siguiente nodo linkedList.head.next = second; second.next = third; third.next = fourth; //Hacer un bucle en LinkedList fourth.next = second; //Imprimir el valor del nodo System.out.print("LinkedList: "); int i = 1; while (i <= 4) { System.out.print(linkedList.head.value + ""); linkedList.head = linkedList.head.next; i++; } //Llamar al método para verificar el bucle boolean loop = linkedList.checkLoop(); if(loop) { System.out.println("\nHay un bucle en LinkedList."); } else { System.out.println("\nNo hay bucle en LinkedList."); } } }
Resultados de salida
LinkedList: 1 2 3 4 En LinkedList hay un bucle.
En el ejemplo anterior, ya hemos utilizado Java Implementamos LinkedList. UtilizamosAlgoritmo de búsqueda de bucle de Floydpara verificar si LinkedList tiene un bucle.
Atención al código en el método checkLoop(). Aquí, tenemos dos variables llamadas first, second, que recorren los nodos de LinkedList.
first - Se utiliza en una iteración única2Nodos se recorren
second - Se utiliza en una iteración única1Nodos se recorren.
Dos nodos se recorren a diferentes velocidades. Por lo tanto, si LinkedList tiene un bucle, se encontrarán.