Programma Java per implementare LinkedList

In questo esempio, impareremo a implementare la struttura dei dati dell'elenco collegato in Java.

Per comprendere questo esempio, è necessario conoscere i seguenti argomenti di programmazione Java:

  • Java LinkedList
  • Java Generics

Esempio 1: programma Java per implementare LinkedList

 class LinkedList ( // create an object of Node class // represent the head of the linked list Node head; // static inner class static class Node ( int value; // connect each node to next node Node next; Node(int d) ( value = d; next = null; ) ) public static void main(String() args) ( // create an object of LinkedList LinkedList linkedList = new LinkedList(); // assign values to each linked list node linkedList.head = new Node(1); Node second = new Node(2); Node third = new Node(3); // connect each node of linked list to next node linkedList.head.next = second; second.next = third; // printing node-value System.out.print("LinkedList: "); while (linkedList.head != null) ( System.out.print(linkedList.head.value + " "); linkedList.head = linkedList.head.next; ) ) )

Produzione

 Elenco collegato: 1 2 3 

Nell'esempio precedente, abbiamo implementato l'elenco collegato singolarmente in Java. Qui, l'elenco collegato è composto da 3 nodi.

Ogni nodo è costituito da valore e successivo. La variabile value rappresenta il valore del nodo e la next rappresenta il collegamento al nodo successivo.

Per conoscere il funzionamento di LinkedList, visita la struttura dei dati di LinkedList.

Esempio 2: implementare LinkedList utilizzando la classe LinkedList

Java fornisce una LinkedListclasse costruita che può essere utilizzata per implementare un elenco collegato.

 import java.util.LinkedList; class Main ( public static void main(String() args)( // create a linked list using the LinkedList class LinkedList animals = new LinkedList(); // Add elements to LinkedList animals.add("Dog"); // add element at the beginning of linked list animals.addFirst("Cat"); // add element at the end of linked list animals.addLast("Horse"); System.out.println("LinkedList: " + animals); // access first element System.out.println("First Element: " + animals.getFirst()); // access last element System.out.println("Last Element: " + animals.getLast()); ) )

Produzione

 Elenco collegato: (gatto, cane, cavallo) Primo elemento: gatto Ultimo elemento: cavallo

Nell'esempio precedente, abbiamo utilizzato la LinkedListclasse per implementare l'elenco collegato in Java. Qui, abbiamo utilizzato i metodi forniti dalla classe per aggiungere elementi e accedere agli elementi dall'elenco collegato.

Notare, abbiamo usato le parentesi angolari () durante la creazione dell'elenco collegato. Rappresenta che l'elenco collegato è di tipo generico.

Articoli interessanti...