Java program to implement linkedlist
Here's an example Java program that demonstrates how to implement a LinkedList data structure in Java:
public class LinkedList<T> {
private Node head;
private class Node {
T data;
Node next;
public Node(T data) {
this.data = data;
this.next = null;
}
}
public LinkedList() {
head = null;
}
public void add(T data) {
Node newNode = new Node(data);
if (head == null) {
head = newNode;
} else {
Node current = head;
while (current.next != null) {
current = current.next;
}
current.next = newNode;
}
}
public void remove(T data) {
if (head == null) {
return;
}
if (head.data.equals(data)) {
head = head.next;
return;
}
Node current = head;
while (current.next != null) {
if (current.next.data.equals(data)) {
current.next = current.next.next;
return;
}
current = current.next;
}
}
public void print() {
Node current = head;
while (current != null) {
System.out.print(current.data + " ");
current = current.next;
}
System.out.println();
}
}
In this program, we define a generic LinkedList class with a private Node class nested inside it. Each Node object has a data field and a next field, which points to the next node in the linked list.
The LinkedList class has three methods:
- The
add()method adds a new node to the end of the linked list. - The
remove()method removes the first node in the linked list that contains the specified data. - The
print()method prints the contents of the linked list to the console.
To use this LinkedList class, you can create a new instance of it and call its methods:
public static void main(String[] args) {
LinkedList<String> list = new LinkedList<>();
list.add("apple");
list.add("banana");
list.add("cherry");
list.add("date");
list.print(); // Output: apple banana cherry date
list.remove("banana");
list.print(); // Output: apple cherry date
}
In this example, we create a new LinkedList object of strings, add some elements to it, and print its contents to the console. We then remove an element from the list and print its contents again to verify that the element was removed.
When you run the program, the output will be:
apple banana cherry date apple cherry date
As you can see, the LinkedList implementation successfully adds, removes, and prints elements of the linked list.
