Reputation: 853
I see JDK implementation of LinkedList
internally contains Node
inner class, which contains the address to next and previous.
So my doubt isn't LinkedList
in java a doubly linked list. If not, why?
And how to implement our own doubly linked list?
Upvotes: 43
Views: 78747
Reputation: 1
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.
Upvotes: -1
Reputation: 7876
What's missing in java LinkedList is ability to store pointers. Consider the following code:
var list = new LinkedList<Integer>();
var head = list.listIterator();
var anotherHead = list.listIterator();
anotherHead.add(5);
System.out.println(head.next());
We would like to store a pointer to the head and use it later. No way. As soon as the list gets modified (through other pointer for example) our pointer becomes invalid. In a normal linked list the old pointer should still allow us to navigate through the list.
Upvotes: 0
Reputation: 393936
Yes, LinkedList
is a doubly linked list, as the Javadoc mentions :
Doubly-linked list implementation of the List and Deque interfaces. Implements all optional list operations, and permits all elements (including null).
All of the operations perform as could be expected for a doubly-linked list. Operations that index into the list will traverse the list from the beginning or the end, whichever is closer to the specified index.
Upvotes: 74