Implement Custom Doubly Linked List in Java

A Doubly Linked List is a collection of nodes in a linear sequence.

Furthermore, each node also stores the below three things:

  1. Data 
  2. A reference to the next node
  3. A reference to the previous node
Implement Custom Doubly Linked List in Java

Let’s try to implement Doubly Linked List in Java.

It will have the below methods:

  1. addToFirst
  2. addToLast
  3. traverse
package com.java.datastructure;
public class DoublyLinkedList {
	private Node head;
	private Node tail;
	// Adds the element as the head
	public void addToFirst(String data) {
		if (head == null) {
			head = new Node(data, null, null);
			tail = head;
		} else {		
			Node newNode = new Node(data, head, null);
			head.setPrevious(newNode);
			head = newNode;
		}
	}
	// Adds the element as the tail
	public void addToLast(String data) {
		if (head == null) {
			head = new Node(data, null, null);
			tail = head;
		} else {
			Node newNode = new Node(data, null, tail);
			tail.setNext(newNode);
			tail = newNode;
		}
	}
	public void traverse() {
		if (head == null) {
			System.out.println("No elements in the DoublyLinkedList");
			return;
		}
		Node node = head;
		int i = 0;
		while (node != null) {
			if (i > 0) {
				System.out.print(" ==> ");
			}
			System.out.print(node);
			node = node.getNext();
			i++;
		}
	}
	public static void main(String[] args) {
		DoublyLinkedList linkedList = new DoublyLinkedList();
		linkedList.addToLast("Rochit");
		linkedList.addToLast("Gyan");
		linkedList.addToLast("Praveen");
		linkedList.addToFirst("Vivek");
		linkedList.traverse();
	}
}
class Node {
	public String getData() {
		return data;
	}
	public Node getNext() {
		return next;
	}
	public Node(String data, Node next, Node previous) {
		this.data = data;
		this.next = next;
		this.previous = previous;
	}
	public void setData(String data) {
		this.data = data;
	}
	public void setNext(Node next) {
		this.next = next;
	}
	public Node getPrevious() {
		return previous;
	}
	public void setPrevious(Node previous) {
		this.previous = previous;
	}
	@Override
	public String toString() {
		String nextData = next != null ? next.getData() : null;
		String previousData = previous != null ? previous.getData() : null;
		return "Node [previous=" + previousData +", data=" + data + ", next=" + nextData +  "]";
	}
	private String data;
	private Node next;
	private Node previous;
}

Output

Node [previous=null, data=Vivek, next=Rochit] ==> Node [previous=Vivek, data=Rochit, next=Gyan] ==> Node [previous=Rochit, data=Gyan, next=Praveen] ==> Node [previous=Gyan, data=Praveen, next=null]

Related Article

Please go through the below related article.

Create a Singly Linked List in Java

Leave a Reply

Your email address will not be published. Required fields are marked *