English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
In this instance, we will learn how to implement the linked list data structure in Java.
To understand this example, please ensure that you first visit the following tutorials:
class LinkedList {}} //Create an object of the Node class //Represents the head of the linked list Node head; //Static inner class static class Node { int value; //Connect each node to the next node Node next; Node(int d) { value = d; next = null; } } public static void main(String[] args) { //Create a LinkedList object 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 the linked list to the next node linkedList.head.next = second; second.next = third; //Print node value System.out.print("LinkedList: "); while (linkedList.head != null) { System.out.print(linkedList.head.value + ""); linkedList.head = linkedList.head.next; } } }
Output Result
LinkedList: 1 2 3
In the above example, we have implemented a singly linked list in Java. Here, the linked list is made up of3nodes make up.
Each node consists of value and next. The value variable represents the value of the node and next represents the link to the next node.
Java provides a built-in LinkedList class that can be used to implement a linked list.
import java.util.LinkedList; class Main { public static void main(String[] args){ //Create a linked list using the LinkedList class LinkedList<String> animals = new LinkedList<>(); //Add an element to the LinkedList animals.add("Dog"); //Add an element to the beginning of the linked list animals.addFirst("Cat"); // Add an element at the end of the list animals.addLast("Horse"); System.out.println("LinkedList: " + animals); // Access the first element System.out.println("First element: " + animals.getFirst()); //Access the last element System.out.println("Last element: " + animals.getLast()); } }
Output Result
LinkedList: [Cat, Dog, Horse] First element: Cat Last element: Horse
In the above example, we implemented a linked list in Java using the LinkedList class. Here, we use the methods provided by the class to add elements to and access elements from the list.
Note that we used angle brackets <String> when creating the list. It indicates that the list is a generic type. For more information about generics, please visitJava Generics.