How to create a Doubly Linked List in Java

How to create double linked list in Java

In Double Linked List we have each node pointing to the previous and next node. Here we will see how to create a custom Double Linked List in java.
Some properties of linked list is that, it has a node that can contain some value and then each node is linked to next node and also previous node. That's why we can traverse the linked list sequentially given we know the starting (head) node or last (tail) node.
Custom Linked List
class MyLinkedList<E> {

	/* first points to head of the list */
	public Node<E> first = null;

	/* last points to tail of the list */
	public Node<E> last = null;

	/**
	 * Add item to tail (end) of the List
	 * 
	 * @param item
	 * @return
	 */
	public boolean add(E item) {
		Node<E> newNode = new Node<E>(last, item, null);

		if (last == null) {
			// last points to the new node created
			first = newNode;
		} else {
			last.next = newNode;
		}
		// update last so that it points to the new node
		last = newNode;
		return true;
	}

	static class Node<E> {
		public E value;
		public Node<E> next;
		public Node<E> prev;

		Node(Node<E> prev, E element, Node<E> next) {
			this.value = element;
			this.next = next;
			this.prev = prev;
		}
	}

}
In the above implementation we have defined the main class MyLinkedList and inside it we defined a generic static class Node. Each Node object can hold a value and has links to previous (prev) and next nodes.
Create Instance of MyLinkedList
//create instance
MyLinkedList<Integer> list = new MyLinkedList<Integer>();

//add values 1,2,3,4,5
list.add(1);
list.add(2);
list.add(3);
list.add(4);
list.add(5);
Print the content of the node
//Get the first node (head node) and then print it by traversing all nodes
MyLinkedList.Node<Integer> node = list.first;
while (node != null) {
	System.out.println("Content of Node: " + node.value);
	node = node.next;
}
Terminal
Output
Content of Node: 1
Content of Node: 2
Content of Node: 3
Content of Node: 4
Content of Node: 5

No comments :

Post a Comment

Please leave your message queries or suggetions.