This Java code implements a double linked list using the built-in LinkedList class from the Java Collections Framework. The DoubleLinkedList class has methods to add elements, remove elements, and print the list in both forward and backward directions.
import java.util.LinkedList;
import java.util.ListIterator;
class DoubleLinkedList {
LinkedList linklist = new LinkedList();
public void add(int item) {
linklist.add(item);
}
public int remove() {
return (int) linklist.remove();
}
public void printlist() {
ListIterator<Integer> lstr = linklist.listIterator();
System.out.println("printing data forward direction");
while (lstr.hasNext()) {
System.out.println(lstr.next());
}
System.out.println("printing data backward direction");
while (lstr.hasPrevious()) {
System.out.println(lstr.previous());
}
}
}
public class DoubleLinkedListUsingBuiltInLinkedList {
public static void main(String[] args) {
DoubleLinkedList d1 = new DoubleLinkedList();
d1.add(10);
d1.add(20);
d1.add(30);
d1.printlist();
}
}
Note that this implementation uses the built-in LinkedList class, which is a doubly-linked list. This means that each node in the list has references to both the previous and next nodes, allowing for efficient insertion and removal of elements at any position in the list.
Also, the printlist method uses a ListIterator to print the elements in both forward and backward directions. The ListIterator is a specialized iterator that allows for bidirectional traversal of the list.
Overall, this code demonstrates how to use the built-in LinkedList class to implement a double linked list and perform basic operations like adding, removing, and printing elements.