BeginnersBook

  • Home
  • Java
    • Java OOPs
    • Java Collections
    • Java Examples
  • C
    • C Examples
  • C++
    • C++ Examples
  • DBMS
  • Computer Network
  • Python
    • Python Examples
  • More…
    • jQuery
    • Kotlin
    • WordPress
    • SEO
    • JSON
    • JSP
    • JSTL
    • Servlet
    • MongoDB
    • XML
    • Perl

How to Insert an item in Doubly LinkedList in Java

Last Updated: May 23, 2024 by Chaitanya Singh | Filed Under: java

In this tutorial, we will learn how to insert an item in Doubly LinkedList in java at various positions. We will write a Java Program to add an element at the end, beginning or at the specified position in Doubly Linked List.

Java Program to add item at various positions in Doubly LinkedList

The explanation of the program in provided at the end of the program and a brief description is mentioned in the comments.

//A Node represents the element in a Doubly linked list
//An element in Doubly linked list contains the pointer to
//previous as well as next element of the list
class Node {
// Data stored in the node
String data;

//address of previous node in list
Node prev;

//address of next node in list
Node next;

// Constructor of this class will be used to initialize a node
public Node(String data) {
this.data = data;
this.prev = null;
this.next = null;
}
}

class DoublyLinkedList {
//contains the address of first element
Node head;
//contains the address of last element
Node tail;

// Constructor to initialize an empty list
public DoublyLinkedList() {
this.head = null;
this.tail = null;
}

// Method to add a node with given data to the end of the list
public void add(String data) {
// Create a new node with given data
Node newNode = new Node(data);
// If the list is empty
if (head == null) {
// In the case of empty list, set head and tail to
//contain the address of this Node
head = newNode;
tail = newNode;
} else {
// Add the new node after the current tail
tail.next = newNode;
// newNode prev field contains the address of current tail
newNode.prev = tail;
// Now, newNode becomes the tail, so update tail to point this node
tail = newNode;
}
}

// Method to insert a node with given data at the beginning of the list
public void insertAtBeginning(String data) {
// Create a new node with given data
Node newNode = new Node(data);
// If the list is empty
if (head == null) {
// In the case of empty list, set head and tail to
//contain the address of this Node
head = newNode;
tail = newNode;
} else {
// newNode next field contains the address of current head
newNode.next = head;
// Update the prev field of current head to point newNode
head.prev = newNode;
// Now, newNode becomes the first element, Update the head field
head = newNode;
}
}

// Method to insert a node with given data at a specified position in the list
public void insertAtPosition(int position, String data) {
// Create a new node with given data
Node newNode = new Node(data);
// Check for invalid position
if (position <= 0) {
System.out.println("Invalid position");
return;
}
// If inserting at the beginning
if (position == 1) {
insertAtBeginning(data);
return;
}
// Initialize count
int count = 1;
// Start from the head of the list
Node current = head;
// Traverse to the node before the insertion point
while (current != null && count < position - 1) {
current = current.next;
count++;
}
// Check for invalid position
if (current == null) {
System.out.println("Invalid position");
return;
}
// Connect the new node to the next node
newNode.next = current.next;
// Connect the new node to the current node
newNode.prev = current;
// Update the previous reference of the next node
if (current.next != null) {
current.next.prev = newNode;
} else {
// Update the tail if the new node is inserted at the end
tail = newNode;
}
// Update the next reference of the current node
current.next = newNode;
}

// Method to display the elements of the list
public void display() {
// Start from the head of the list
Node current = head;
// If the list is empty
if (head == null) {
System.out.println("Doubly linked list is empty");
return;
}
System.out.println("Nodes of the doubly linked list:");
// Traverse the list until the end
while (current != null) {
// Print the data of the current node
System.out.print(current.data + " <-> ");
// Move to the next node
current = current.next;
}
System.out.println("null");
}
}

public class JavaDoublyLinkedList {
public static void main(String[] args) {
// Create a new doubly linked list
DoublyLinkedList dll = new DoublyLinkedList();
// Add elements to the list
dll.add("apple");
dll.add("banana");
dll.add("orange");

// Display the original doubly linked list
System.out.println("Original doubly linked list:");
dll.display();

// Insert "grape" at the beginning
dll.insertAtBeginning("grape");
// Display the list after inserting "grape" at the beginning
System.out.println("After inserting 'grape' at the beginning:");
dll.display();

// Insert "kiwi" at position 3
dll.insertAtPosition(3, "kiwi");
// Display the list after inserting "kiwi" at position 3
System.out.println("After inserting 'kiwi' at position 3:");
dll.display();
}
}

Output:

Original doubly linked list:
Nodes of the doubly linked list:
apple <-> banana <-> orange <-> null
After inserting 'grape' at the beginning:
Nodes of the doubly linked list:
grape <-> apple <-> banana <-> orange <-> null
After inserting 'kiwi' at position 3:
Nodes of the doubly linked list:
grape <-> apple <-> kiwi <-> banana <-> orange <-> null

Explanation of the program

  1. Node Class:
    • It represents an element of Doubly linked list. Each node contains three fields:
    • data: Stores the value of the node, in this case, a String.
    • prev: Points to the previous node in the list.
    • next: Points to the next node in the list.
  2. DoublyLinkedList Class:
    • This class contains methods to add elements at various positions.
    • It has two fields: head (contains address of first element) and tail (contains address of last element).
    • The constructor of this class initializes an empty list by setting both head and tail to null.
  3. Add Method:
    • The add method inserts the given element at the end of doubly linked list.
    • It checks if the list is empty or not, if empty then new node becomes head and tail both, else add element at the end and update tail.
  4. InsertAtBeginning Method:
    • The insertAtBeginning() method inserts the new element at the beginning of the doubly linked list
    • Update prev field of current head to point new node and update next field of new node to point current head. Update head to point to new node.
  5. InsertAtPosition Method:
    • The insertAtPosition() method inserts the new element at the specified position in the doubly linked list.
    • If the specified position is invalid or less than or equal to 0, it prints an error message and returns.
    • If the position is 1, it calls the insertAtBeginning() method.
    • Otherwise, it updates the next and previous references of the new node and adjacent nodes to insert the new node at the specified position.
  6. Display Method:
    • It traverses the whole list and print all elements.
    • If the list is empty, it prints a message indicating that the list is empty.
  7. Main Method:
    • In the main method, an instance of the DoublyLinkedList class is created.
    • Few elements are added to list using the add() method.
    • The current list is printed.
    • Items are inserted at the beginning and at a specified position using the insertAtBeginning and insertAtPosition methods, respectively.
    • The updated list is displayed after each insert method call.

Related Articles:

  • LinkedList in Java with Examples
  • Search element in Doubly LinkedList in Java
  • Adding elements at the beginning and at the end of LinkedList
  • Add element at the specified index in LinkedList in Java

Tags: Collections, Java-LinkedList

About the Author

I have 15 years of experience in the IT industry, working with renowned multinational corporations. Additionally, I have dedicated over a decade to teaching, allowing me to refine my skills in delivering information in a simple and easily understandable manner.

– Chaitanya

Leave a Reply Cancel reply

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

Java Tutorial

Java Introduction

  • Java Index
  • Java Introduction
  • History of Java
  • Features of Java
  • C++ vs Java
  • JDK vs JRE vs JVM
  • JVM - Java Virtual Machine
  • First Java Program
  • Variables
  • Data Types
  • Operators

Java Flow Control

  • Java If-else
  • Java Switch-Case
  • Java For loop
  • Java while loop
  • Java do-while loop
  • Continue statement
  • break statement

Java Arrays

  • Java Arrays

OOPs Concepts

  • OOPs Concepts
  • Constructor
  • Java String
  • Static keyword
  • Inheritance
  • Types of inheritance
  • Aggregation
  • Association
  • Super Keyword
  • Method overloading
  • Method overriding
  • Overloading vs Overriding
  • Polymorphism
  • Types of polymorphism
  • Static and dynamic binding
  • Abstract class and methods
  • Interface
  • Abstract class vs interface
  • Encapsulation
  • Packages
  • Access modifiers
  • Garbage Collection
  • Inner classes
  • Static import
  • Static constructor

Java Exception Handling

  • Exception handling
  • Java try-catch
  • Java throw
  • Java throws
  • Checked and Unchecked Exceptions
  • Jav try catch finally
  • Exception Examples
  • Exception Propagation

Collections Framework

  • Collections in Java
  • Java ArrayList
  • Java LinkedList
  • Java Vector
  • Java HashSet
  • Java LinkedHashSet
  • Java TreeSet
  • Java HashMap
  • Java TreeMap
  • Java LinkedHashMap
  • Java Queue
  • Java PriorityQueue
  • Java Deque
  • Comparable interface
  • Comparator interface
  • Collections Interview Questions

MORE ...

  • Java Scanner Class
  • Java 8 Features
  • Java 9 Features
  • Java Conversion
  • Java Date
  • Java Multithreading
  • Java I/O
  • Java Serialization
  • Java Regex
  • Java AWT
  • Java Swing
  • Java Enum
  • Java Annotations
  • Java main method
  • Java Interview Q

Copyright © 2012 – 2025 BeginnersBook . Privacy Policy . Sitemap