As a Java programmer, it is essential to have a solid understanding of data structures, particularly LinkedList.
LinkedList is a linear data structure in which each element is connected to the next element through a pointer.
In this tutorial, we will learn how to implement LinkedList in Java.
To begin, we need to create a Node class that will represent each element in our LinkedList.
Each Node will contain the value of the element and a reference to the next Node in the LinkedList.
Here’s the code for the Node class:
class Node { int value; Node next; public Node(int value) { this.value = value; this.next = null; } }
The value variable represents the value of the element, and the next variable represents the reference to the next Node in the LinkedList.
The constructor initializes the value variable and sets the next variable to null.
Next, we need to create a LinkedList class that will contain our Node elements.
The LinkedList class will have a reference to the first Node in the LinkedList.
Here’s the code for the LinkedList class:
class LinkedList { Node head; public LinkedList() { this.head = null; } public void add(int value) { Node newNode = new Node(value); if (head == null) { head = newNode; } else { Node current = head; while (current.next != null) { current = current.next; } current.next = newNode; } } public void printList() { Node current = head; while (current != null) { System.out.print(current.value + " "); current = current.next; } System.out.println(); } }
The LinkedList class has a constructor that initializes the head variable to null.
The add() method adds a new element to the end of the LinkedList. If the LinkedList is empty, it sets the head variable to the new Node.
Otherwise, it iterates through the LinkedList until it reaches the end and sets the next variable of the last Node to the new Node.
The printList() method iterates through the LinkedList and prints each element.
Finally, we can test our LinkedList implementation with the following code:
public static void main(String[] args) { LinkedList list = new LinkedList(); list.add(1); list.add(2); list.add(3); list.printList(); // Output: 1 2 3 }
In this code, we create a new LinkedList and add three elements to it.
We then call the printList() method to print the elements of the LinkedList.
In conclusion, LinkedList is a fundamental data structure in computer science, and it is essential to understand how to implement it in Java.
By following the steps outlined above, you can create your own LinkedList class and begin using it in your Java projects.