Creating a Linked List
To create a linked list, we first need to define the Node
class, which represents an element in the list. Each Node
object contains a data
field to store the value of the element and a next
field to point to the next element in the list.
In Java, the Node
class can be defined as follows:
1class Node {
2 int data;
3 Node next;
4
5 public Node(int data) {
6 this.data = data;
7 this.next = null;
8 }
9}
Once the Node
class is defined, we can create the LinkedList
class to manage the linked list. The LinkedList
class has a head
field to point to the first element in the list.
To create a new linked list, we can initialize the head
to null
, indicating an empty list.
1LinkedList ll = new LinkedList();
To add elements to the linked list, we create a new Node
object with the desired value and set its next
field to null
. If the list is empty, we set the head
to the new node. Otherwise, we traverse the list until we reach the last node and set its next
field to the new node.
Here's an example of adding elements to the linked list:
1ll.add(10);
2ll.add(20);
3ll.add(30);
To display the elements of the linked list, we start at the head
and traverse the list, printing the value of each node.
1ll.display();
The output of the above code would be:
110
220
330
xxxxxxxxxx
}
public class Main {
public static void main(String[] args) {
// Creating an empty linked list
LinkedList ll = new LinkedList();
// Adding elements to the list
ll.add(10);
ll.add(20);
ll.add(30);
// Displaying the list
ll.display();
}
}
class Node {
int data;
Node next;
public Node(int data) {
this.data = data;
this.next = null;
}
}
class LinkedList {
Node head;
public void add(int data) {