¿Cómo puedo crear una estructura de datos de lista enlazada en Java?

¿Cuál es la mejor manera de hacer una lista enlazada en Java?

Solución

La solución obvia para los desarrolladores familiarizados con Java es utilizar la clase LinkedList ya proporcionada en java.util. Digamos, sin embargo, que quieres hacer tu propia implementación por alguna razón. Aquí hay un ejemplo rápido de una lista enlazada que inserta un nuevo enlace al principio de la lista, borra del principio de la lista y hace un bucle a través de la lista para imprimir los enlaces que contiene. Las mejoras a esta implementación incluyen convertirla en una lista enlazada doble, añadiendo métodos para insertar y borrar desde el medio o el final, y añadiendo también métodos obtener y clasificar.

**Nota: En el ejemplo, el objeto Link no contiene realmente otro objeto Link - nextLink es en realidad sólo una referencia a otro link.

class Link {
    public int data1;
    public double data2;
    public Link nextLink;

    //Link constructor
    public Link(int d1, double d2) {
        data1 = d1;
        data2 = d2;
    }

    //Print Link data
    public void printLink() {
        System.out.print("{" + data1 + ", " + data2 + "} ");
    }
}

class LinkList {
    private Link first;

    //LinkList constructor
    public LinkList() {
        first = null;
    }

    //Returns true if list is empty
    public boolean isEmpty() {
        return first == null;
    }

    //Inserts a new Link at the first of the list
    public void insert(int d1, double d2) {
        Link link = new Link(d1, d2);
        link.nextLink = first;
        first = link;
    }

    //Deletes the link at the first of the list
    public Link delete() {
        Link temp = first;
        if(first == null){
         return null;
         //throw new NoSuchElementException(); // this is the better way. 
        }
        first = first.nextLink;
        return temp;
    }

    //Prints list data
    public void printList() {
        Link currentLink = first;
        System.out.print("List: ");
        while(currentLink != null) {
            currentLink.printLink();
            currentLink = currentLink.nextLink;
        }
        System.out.println("");
    }
}  

class LinkListTest {
    public static void main(String[] args) {
        LinkList list = new LinkList();

        list.insert(1, 1.01);
        list.insert(2, 2.02);
        list.insert(3, 3.03);
        list.insert(4, 4.04);
        list.insert(5, 5.05);

        list.printList();

        while(!list.isEmpty()) {
            Link deletedLink = list.delete();
            System.out.print("deleted: ");
            deletedLink.printLink();
            System.out.println("");
        }
        list.printList();
    }
}
Comentarios (6)

Java tiene una implementación de LinkedList, que tal vez quieras comprobar. Puedes descargar el JDK y sus fuentes en java.sun.com.

Comentarios (4)

Utilice java.util.LinkedList. Así:

list = new java.util.LinkedList()
Comentarios (0)