Java Program to Implement Doubly Linked List

Problem Description

Write a Java Program to implement a Doubly Linked List.

What is a Doubly Linked List in Java?

A Doubly Linked List in Java is a data structure that consists of a sequence of nodes, where each node has a reference to both the previous and the next node in the list. This allows for both forward and backward traversal of the list, which is not possible with a singly linked list.

In Java, a Doubly Linked List can be implemented using a custom class that defines the structure of each node and the operations that can be performed on the list. The class would typically have methods to add, remove, and access elements in the list, as well as to traverse the list in both directions.

Doubly Linked List Operations

Here are some commonly used operations on a doubly linked list:

1. Insertion: Add a new node to the list at a given position or at the beginning/end of the list.

advertisement
advertisement
  • addFirst(): This operation inserts a new element at the beginning of the list. To do this, the list’s head pointer is updated to point to the new node, and the new node’s next pointer is set to the old head node. If the list was empty, the tail pointer is also updated to point to the new node.
  • addLast(): This operation inserts a new element at the end of the list. To do this, the list’s tail pointer is updated to point to the new node, and the new node’s previous pointer is set to the old tail node. If the list was empty, the head pointer is also updated to point to the new node.

2. Deletion: Remove a node from the list at a given position or by specifying the node to be removed.

  • removeFirst(): This operation removes the first element from the list. To do this, the head pointer is updated to point to the second node in the list, and the new head node’s previous pointer is set to null. If the list becomes empty after the removal, the tail pointer is also updated to null.
  • removeLast(): This operation removes the last element from the list. To do this, the tail pointer is updated to point to the second-to-last node in the list, and the new tail node’s next pointer is set to null. If the list becomes empty after the removal, the head pointer is also updated to null.

3. Traversal: Visit each node in the list in forward or backward direction.

  • get(int index): This operation returns the element at the specified index. To do this, the list is traversed either from the head or the tail depending on which direction is shorter, until the node at the specified index is reached. Then, the data in that node is returned.
Program/Source Code

Here is the source code of the Java program to implement Doubly Linked List. The Java program is successfully compiled and run on a Windows system. The program output is also shown below.

Note: Join free Sanfoundry classes at Telegram or Youtube
  1. /*
  2.  *  Java Program to Implement Doubly Linked List
  3.  */
  4.  
  5. import java.util.Scanner;
  6.  
  7. /*  Class Node  */
  8. class Node
  9. {
  10.     protected int data;
  11.     protected Node next, prev;
  12.  
  13.     /* Constructor */
  14.     public Node()
  15.     {
  16.         next = null;
  17.         prev = null;
  18.         data = 0;
  19.     }
  20.     /* Constructor */
  21.     public Node(int d, Node n, Node p)
  22.     {
  23.         data = d;
  24.         next = n;
  25.         prev = p;
  26.     }
  27.     /* Function to set link to next node */
  28.     public void setLinkNext(Node n)
  29.     {
  30.         next = n;
  31.     }
  32.     /* Function to set link to previous node */
  33.     public void setLinkPrev(Node p)
  34.     {
  35.         prev = p;
  36.     }    
  37.     /* Funtion to get link to next node */
  38.     public Node getLinkNext()
  39.     {
  40.         return next;
  41.     }
  42.     /* Function to get link to previous node */
  43.     public Node getLinkPrev()
  44.     {
  45.         return prev;
  46.     }
  47.     /* Function to set data to node */
  48.     public void setData(int d)
  49.     {
  50.         data = d;
  51.     }
  52.     /* Function to get data from node */
  53.     public int getData()
  54.     {
  55.         return data;
  56.     }
  57. }
  58.  
  59. /* Class linkedList */
  60. class linkedList
  61. {
  62.     protected Node start;
  63.     protected Node end ;
  64.     public int size;
  65.  
  66.     /* Constructor */
  67.     public linkedList()
  68.     {
  69.         start = null;
  70.         end = null;
  71.         size = 0;
  72.     }
  73.     /* Function to check if list is empty */
  74.     public boolean isEmpty()
  75.     {
  76.         return start == null;
  77.     }
  78.     /* Function to get size of list */
  79.     public int getSize()
  80.     {
  81.         return size;
  82.     }
  83.     /* Function to insert element at begining */
  84.     public void insertAtStart(int val)
  85.     {
  86.         Node nptr = new Node(val, null, null);        
  87.         if(start == null)
  88.         {
  89.             start = nptr;
  90.             end = start;
  91.         }
  92.         else
  93.         {
  94.             start.setLinkPrev(nptr);
  95.             nptr.setLinkNext(start);
  96.             start = nptr;
  97.         }
  98.         size++;
  99.     }
  100.     /* Function to insert element at end */
  101.     public void insertAtEnd(int val)
  102.     {
  103.         Node nptr = new Node(val, null, null);        
  104.         if(start == null)
  105.         {
  106.             start = nptr;
  107.             end = start;
  108.         }
  109.         else
  110.         {
  111.             nptr.setLinkPrev(end);
  112.             end.setLinkNext(nptr);
  113.             end = nptr;
  114.         }
  115.         size++;
  116.     }
  117.     /* Function to insert element at position */
  118.     public void insertAtPos(int val , int pos)
  119.     {
  120.         Node nptr = new Node(val, null, null);    
  121.         if (pos == 1)
  122.         {
  123.             insertAtStart(val);
  124.             return;
  125.         }            
  126.         Node ptr = start;
  127.         for (int i = 2; i <= size; i++)
  128.         {
  129.             if (i == pos)
  130.             {
  131.                 Node tmp = ptr.getLinkNext();
  132.                 ptr.setLinkNext(nptr);
  133.                 nptr.setLinkPrev(ptr);
  134.                 nptr.setLinkNext(tmp);
  135.                 tmp.setLinkPrev(nptr);
  136.             }
  137.             ptr = ptr.getLinkNext();            
  138.         }
  139.         size++ ;
  140.     }
  141.     /* Function to delete node at position */
  142.     public void deleteAtPos(int pos)
  143.     {        
  144.         if (pos == 1) 
  145.         {
  146.             if (size == 1)
  147.             {
  148.                 start = null;
  149.                 end = null;
  150.                 size = 0;
  151.                 return; 
  152.             }
  153.             start = start.getLinkNext();
  154.             start.setLinkPrev(null);
  155.             size--; 
  156.             return ;
  157.         }
  158.         if (pos == size)
  159.         {
  160.             end = end.getLinkPrev();
  161.             end.setLinkNext(null);
  162.             size-- ;
  163.         }
  164.         Node ptr = start.getLinkNext();
  165.         for (int i = 2; i <= size; i++)
  166.         {
  167.             if (i == pos)
  168.             {
  169.                 Node p = ptr.getLinkPrev();
  170.                 Node n = ptr.getLinkNext();
  171.  
  172.                 p.setLinkNext(n);
  173.                 n.setLinkPrev(p);
  174.                 size-- ;
  175.                 return;
  176.             }
  177.             ptr = ptr.getLinkNext();
  178.         }        
  179.     }    
  180.     /* Function to display status of list */
  181.     public void display()
  182.     {
  183.         System.out.print("\nDoubly Linked List = ");
  184.         if (size == 0) 
  185.         {
  186.             System.out.print("empty\n");
  187.             return;
  188.         }
  189.         if (start.getLinkNext() == null) 
  190.         {
  191.             System.out.println(start.getData() );
  192.             return;
  193.         }
  194.         Node ptr = start;
  195.         System.out.print(start.getData()+ " <-> ");
  196.         ptr = start.getLinkNext();
  197.         while (ptr.getLinkNext() != null)
  198.         {
  199.             System.out.print(ptr.getData()+ " <-> ");
  200.             ptr = ptr.getLinkNext();
  201.         }
  202.         System.out.print(ptr.getData()+ "\n");
  203.     }
  204. }
  205.  
  206. /* Class DoublyLinkedList */
  207. public class DoublyLinkedList
  208. {    
  209.     public static void main(String[] args)
  210.     {            
  211.         Scanner scan = new Scanner(System.in);
  212.         /* Creating object of linkedList */
  213.         linkedList list = new linkedList(); 
  214.         System.out.println("Doubly Linked List Test\n");          
  215.         char ch;
  216.         /*  Perform list operations  */
  217.         do
  218.         {
  219.             System.out.println("\nDoubly Linked List Operations\n");
  220.             System.out.println("1. insert at begining");
  221.             System.out.println("2. insert at end");
  222.             System.out.println("3. insert at position");
  223.             System.out.println("4. delete at position");
  224.             System.out.println("5. check empty");
  225.             System.out.println("6. get size");
  226.             System.out.println("Enter your Choice:");
  227.             int choice = scan.nextInt();            
  228.             switch (choice)
  229.             {
  230.             case 1 : 
  231.                 System.out.println("Enter integer element to insert");
  232.                 list.insertAtStart( scan.nextInt() );                     
  233.                 break;                          
  234.             case 2 : 
  235.                 System.out.println("Enter integer element to insert");
  236.                 list.insertAtEnd( scan.nextInt() );                     
  237.                 break;                         
  238.             case 3 : 
  239.                 System.out.println("Enter integer element to insert");
  240.                 int num = scan.nextInt() ;
  241.                 System.out.println("Enter position");
  242.                 int pos = scan.nextInt() ;
  243.                 if (pos < 1 || pos > list.getSize() )
  244.                     System.out.println("Invalid position\n");
  245.                 else
  246.                     list.insertAtPos(num, pos);
  247.                 break;                                          
  248.             case 4 : 
  249.                 System.out.println("Enter position");
  250.                 int p = scan.nextInt() ;
  251.                 if (p < 1 || p > list.getSize() )
  252.                     System.out.println("Invalid position\n");
  253.                 else
  254.                     list.deleteAtPos(p);
  255.                 break;     
  256.             case 5 : 
  257.                 System.out.println("Empty status = "+ list.isEmpty());
  258.                 break;            
  259.             case 6 : 
  260.                 System.out.println("Size = "+ list.getSize() +" \n");
  261.                 break;                         
  262.             default : 
  263.                 System.out.println("Wrong Entry \n ");
  264.                 break;   
  265.             }    
  266.             /*  Display List  */ 
  267.             list.display();
  268.             System.out.println("\nDo you want to continue (Type y or n) \n");
  269.             ch = scan.next().charAt(0);    
  270.  
  271.         } while (ch == 'Y'|| ch == 'y');               
  272.     }
  273. }
Program Explanation

1. The Node class defines a node in the doubly linked list. It has two constructors, one with no arguments and one with three arguments (data, next, and prev).
2. The setLinkNext, setLinkPrev, getLinkNext, getLinkPrev, setData, and getData methods are used to set and get the data and links of a node.
3. The linkedList class defines the doubly linked list. It has a constructor with no arguments that initializes the start and end pointers to null and the size variable to 0. Here are some methods:

  • The isEmpty method checks if the list is empty.
  • The getSize method returns the size of the list.
  • The insertAtStart method inserts a node at the beginning of the list.
  • The insertAtEnd method inserts a node at the end of the list.
  • The insertAtPos method inserts a node at a specific position in the list.
  • The deleteAtPos method deletes a node at a specific position in the list.
  • The display method displays the status of the list.

4. The main method in the DoublyLinkedList class creates an object of the linkedList class and performs the list operations based on user input.
5. It displays a menu of options, including insertion at the beginning, insertion at the end, insertion at a specific position, deletion at a specific position, and display.
6. The user selects an option by entering a number, and the program calls the corresponding method of the linkedList class to perform the operation.
7. The program continues to display the menu of options until the user chooses to exit.

advertisement
Program Output:
Doubly Linked List Test
 
 
Doubly Linked List Operations
 
1. insert at begining
2. insert at end
3. insert at position
4. delete at position
5. check empty
6. get size
1
Enter integer element to insert
5
 
Doubly Linked List = 5
 
Do you want to continue (Type y or n)
 
y
 
Doubly Linked List Operations
 
1. insert at begining
2. insert at end
3. insert at position
4. delete at position
5. check empty
6. get size
Enter your Choice:
1
Enter integer element to insert
2
 
Doubly Linked List = 2 <-> 5
 
Do you want to continue (Type y or n)
 
y
 
Doubly Linked List Operations
 
1. insert at begining
2. insert at end
3. insert at position
4. delete at position
5. check empty
6. get size
Enter your Choice:
2
Enter integer element to insert
6
 
Doubly Linked List = 2 <-> 5 <-> 6
 
Do you want to continue (Type y or n)
 
y
 
Doubly Linked List Operations
 
1. insert at begining
2. insert at end
3. insert at position
4. delete at position
5. check empty
6. get size
Enter your Choice:
1
Enter integer element to insert
7
 
Doubly Linked List = 7 <-> 2 <-> 5 <-> 6
 
Do you want to continue (Type y or n)
 
y
 
Doubly Linked List Operations
 
1. insert at begining
2. insert at end
3. insert at position
4. delete at position
5. check empty
6. get size
Enter your Choice:
3
Enter integer element to insert
3
Enter position
3
 
Doubly Linked List = 7 <-> 2 <-> 3 <-> 5 <-> 6
 
Do you want to continue (Type y or n)
 
y
 
Doubly Linked List Operations
 
1. insert at begining
2. insert at end
3. insert at position
4. delete at position
5. check empty
6. get size
Enter your Choice:
4
Enter position
2
 
Doubly Linked List = 7 <-> 3 <-> 5 <-> 6
 
Do you want to continue (Type y or n)
 
y
 
Doubly Linked List Operations
 
1. insert at begining
2. insert at end
3. insert at position
4. delete at position
5. check empty
6. get size
Enter your Choice:
3
Enter integer element to insert
4
Enter position
4
 
Doubly Linked List = 7 <-> 3 <-> 5 <-> 4 <-> 6
 
Do you want to continue (Type y or n)
 
y
 
Doubly Linked List Operations
 
1. insert at begining
2. insert at end
3. insert at position
4. delete at position
5. check empty
6. get size
Enter your Choice:
6
Size = 5
 
 
Doubly Linked List = 7 <-> 3 <-> 5 <-> 4 <-> 6
 
Do you want to continue (Type y or n)
 
y
 
Doubly Linked List Operations
 
1. insert at begining
2. insert at end
3. insert at position
4. delete at position
5. check empty
6. get size
Enter your Choice:
4
Enter position
1
 
Doubly Linked List = 3 <-> 5 <-> 4 <-> 6
 
Do you want to continue (Type y or n)
 
y
 
Doubly Linked List Operations
 
1. insert at begining
2. insert at end
3. insert at position
4. delete at position
5. check empty
6. get size
Enter your Choice:
4
Enter position
2
 
Doubly Linked List = 3 <-> 4 <-> 6
 
Do you want to continue (Type y or n)
 
y
 
Doubly Linked List Operations
 
1. insert at begining
2. insert at end
3. insert at position
4. delete at position
5. check empty
6. get size
Enter your Choice:
4
Enter position
2
 
Doubly Linked List = 3 <-> 6
 
Do you want to continue (Type y or n)
 
y
 
Doubly Linked List Operations
 
1. insert at begining
2. insert at end
3. insert at position
4. delete at position
5. check empty
6. get size
Enter your Choice:
4
Enter position
1
 
Doubly Linked List = 6
 
Do you want to continue (Type y or n)
 
y
 
Doubly Linked List Operations
 
1. insert at begining
2. insert at end
3. insert at position
4. delete at position
5. check empty
6. get size
Enter your Choice:
4
Enter position
1
 
Doubly Linked List = empty
 
Do you want to continue (Type y or n)
 
y
 
Doubly Linked List Operations
 
1. insert at begining
2. insert at end
3. insert at position
4. delete at position
5. check empty
6. get size
Enter your Choice:
5
Empty status = true
 
Doubly Linked List = empty
 
Do you want to continue (Type y or n)
 
n

To practice programs on every topic in Java, please visit “Programming Examples in Java”, “Data Structures in Java” and “Algorithms in Java”.

advertisement
If you find any mistake above, kindly email to [email protected]

advertisement
advertisement
Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification contest to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!

Youtube | Telegram | LinkedIn | Instagram | Facebook | Twitter | Pinterest
Manish Bhojasia - Founder & CTO at Sanfoundry
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He lives in Bangalore, and focuses on development of Linux Kernel, SAN Technologies, Advanced C, Data Structures & Alogrithms. Stay connected with him at LinkedIn.

Subscribe to his free Masterclasses at Youtube & discussions at Telegram SanfoundryClasses.