• Java Data Structures Tutorial

Java Data Structures - Doubly linked lists



Doubly Linked List is a variation of Linked list in which navigation is possible in both ways, either forward and backward easily as compared to Single Linked List. Following are the important terms to understand the concept of doubly linked list.

Link − Each link of a linked list can store a data called an element.

Next − Each link of a linked list contains a link to the next link called Next.

Prev − Each link of a linked list contains a link to the previous link called Prev.

LinkedList − A Linked List contains the connection link to the first link called First and to the last link called Last.

Doubly Linked List Representation

Doubly Linked List
  • Doubly Linked List contains a link element called first and last.
  • Each link carries a data field(s) and two link fields called next and prev.
  • Each link is linked with its next link using its next link.
  • Each link is linked with its previous link using its previous link.
  • The last link carries a link as null to mark the end of the list.

Example

class Node{
   int data;
   Node preNode, nextNode, CurrentNode;
   Node() {
      preNode = null;
      nextNode = null; 
   }
   Node(int data) {
      this.data = data;
   }
}

public class DoublyLinked {
   Node head, tail;
   int size;   
   public void printData() {
      System.out.println("         ");
      Node node = head;
      while(node !=null) {
         System.out.println(node.data);
         node = node.nextNode;
      }
      System.out.println( );  
   }
   public void insertStart(int data) {
      Node node = new Node();
      node.data = data;
      node.nextNode = head;
      node.preNode = null;
      if(head!=null) {
         head.preNode = node;
      }
      head = node;
      if(tail == null) {
         tail = node;
      }
      size++;   
   }
   public void insertEnd(int data) {
      Node node = new Node();
      node.data = data;
      node.nextNode = null;
      node.preNode = tail;
      
      if(tail!=null) {
         tail.preNode = node;
      }
      tail = node;
      if(head == null) {
         head = node;
      }
      size++;   
   }   
   public static void main(String args[]) {   
      DoublyLinked dl = new DoublyLinked();
      dl.insertStart(10);
      dl.insertStart(20);
      dl.insertStart(30);
      dl.insertStart(1);
      dl.insertStart(56);
      dl.insertStart(40);
      dl.printData();
   }
}

Output

40
56
1
30
20
10
Advertisements