- Blog Categories
- Software Development
- Data Science
- AI/ML
- Marketing
- General
- MBA
- Management
- Legal
- Software Development Projects and Ideas
- 12 Computer Science Project Ideas
- 28 Beginner Software Projects
- Top 10 Engineering Project Ideas
- Top 10 Easy Final Year Projects
- Top 10 Mini Projects for Engineers
- 25 Best Django Project Ideas
- Top 20 MERN Stack Project Ideas
- Top 12 Real Time Projects
- Top 6 Major CSE Projects
- 12 Robotics Projects for All Levels
- Java Programming Concepts
- Abstract Class in Java and Methods
- Constructor Overloading in Java
- StringBuffer vs StringBuilder
- Java Identifiers: Syntax & Examples
- Types of Variables in Java Explained
- Composition in Java: Examples
- Append in Java: Implementation
- Loose Coupling vs Tight Coupling
- Integrity Constraints in DBMS
- Different Types of Operators Explained
- Career and Interview Preparation in IT
- Top 14 IT Courses for Jobs
- Top 20 Highest Paying Languages
- 23 Top CS Interview Q&A
- Best IT Jobs without Coding
- Software Engineer Salary in India
- 44 Agile Methodology Interview Q&A
- 10 Software Engineering Challenges
- Top 15 Tech's Daily Life Impact
- 10 Best Backends for React
- Cloud Computing Reference Models
- Web Development and Security
- Find Installed NPM Version
- Install Specific NPM Package Version
- Make API Calls in Angular
- Install Bootstrap in Angular
- Use Axios in React: Guide
- StrictMode in React: Usage
- 75 Cyber Security Research Topics
- Top 7 Languages for Ethical Hacking
- Top 20 Docker Commands
- Advantages of OOP
- Data Science Projects and Applications
- 42 Python Project Ideas for Beginners
- 13 Data Science Project Ideas
- 13 Data Structure Project Ideas
- 12 Real-World Python Applications
- Python Banking Project
- Data Science Course Eligibility
- Association Rule Mining Overview
- Cluster Analysis in Data Mining
- Classification in Data Mining
- KDD Process in Data Mining
- Data Structures and Algorithms
- Binary Tree Types Explained
- Binary Search Algorithm
- Sorting in Data Structure
- Binary Tree in Data Structure
- Binary Tree vs Binary Search Tree
- Recursion in Data Structure
- Data Structure Search Methods: Explained
- Binary Tree Interview Q&A
- Linear vs Binary Search
- Priority Queue Overview
- Python Programming and Tools
- Top 30 Python Pattern Programs
- List vs Tuple
- Python Free Online Course
- Method Overriding in Python
- Top 21 Python Developer Skills
- Reverse a Number in Python
- Switch Case Functions in Python
- Info Retrieval System Overview
- Reverse a Number in Python
- Real-World Python Applications
- Data Science Careers and Comparisons
- Data Analyst Salary in India
- Data Scientist Salary in India
- Free Excel Certification Course
- Actuary Salary in India
- Data Analyst Interview Guide
- Pandas Interview Guide
- Tableau Filters Explained
- Data Mining Techniques Overview
- Data Analytics Lifecycle Phases
- Data Science Vs Analytics Comparison
- Artificial Intelligence and Machine Learning Projects
- Exciting IoT Project Ideas
- 16 Exciting AI Project Ideas
- 45+ Interesting ML Project Ideas
- Exciting Deep Learning Projects
- 12 Intriguing Linear Regression Projects
- 13 Neural Network Projects
- 5 Exciting Image Processing Projects
- Top 8 Thrilling AWS Projects
- 12 Engaging AI Projects in Python
- NLP Projects for Beginners
- Concepts and Algorithms in AIML
- Basic CNN Architecture Explained
- 6 Types of Regression Models
- Data Preprocessing Steps
- Bagging vs Boosting in ML
- Multinomial Naive Bayes Overview
- Bayesian Network Example
- Bayes Theorem Guide
- Top 10 Dimensionality Reduction Techniques
- Neural Network Step-by-Step Guide
- Technical Guides and Comparisons
- Make a Chatbot in Python
- Compute Square Roots in Python
- Permutation vs Combination
- Image Segmentation Techniques
- Generative AI vs Traditional AI
- AI vs Human Intelligence
- Random Forest vs Decision Tree
- Neural Network Overview
- Perceptron Learning Algorithm
- Selection Sort Algorithm
- Career and Practical Applications in AIML
- AI Salary in India Overview
- Biological Neural Network Basics
- Top 10 AI Challenges
- Production System in AI
- Top 8 Raspberry Pi Alternatives
- Top 8 Open Source Projects
- 14 Raspberry Pi Project Ideas
- 15 MATLAB Project Ideas
- Top 10 Python NLP Libraries
- Naive Bayes Explained
- Digital Marketing Projects and Strategies
- 10 Best Digital Marketing Projects
- 17 Fun Social Media Projects
- Top 6 SEO Project Ideas
- Digital Marketing Case Studies
- Coca-Cola Marketing Strategy
- Nestle Marketing Strategy Analysis
- Zomato Marketing Strategy
- Monetize Instagram Guide
- Become a Successful Instagram Influencer
- 8 Best Lead Generation Techniques
- Digital Marketing Careers and Salaries
- Digital Marketing Salary in India
- Top 10 Highest Paying Marketing Jobs
- Highest Paying Digital Marketing Jobs
- SEO Salary in India
- Content Writer Salary Guide
- Digital Marketing Executive Roles
- Career in Digital Marketing Guide
- Future of Digital Marketing
- MBA in Digital Marketing Overview
- Digital Marketing Techniques and Channels
- 9 Types of Digital Marketing Channels
- Top 10 Benefits of Marketing Branding
- 100 Best YouTube Channel Ideas
- YouTube Earnings in India
- 7 Reasons to Study Digital Marketing
- Top 10 Digital Marketing Objectives
- 10 Best Digital Marketing Blogs
- Top 5 Industries Using Digital Marketing
- Growth of Digital Marketing in India
- Top Career Options in Marketing
- Interview Preparation and Skills
- 73 Google Analytics Interview Q&A
- 56 Social Media Marketing Q&A
- 78 Google AdWords Interview Q&A
- Top 133 SEO Interview Q&A
- 27+ Digital Marketing Q&A
- Digital Marketing Free Course
- Top 9 Skills for PPC Analysts
- Movies with Successful Social Media Campaigns
- Marketing Communication Steps
- Top 10 Reasons to Be an Affiliate Marketer
- Career Options and Paths
- Top 25 Highest Paying Jobs India
- Top 25 Highest Paying Jobs World
- Top 10 Highest Paid Commerce Job
- Career Options After 12th Arts
- Top 7 Commerce Courses Without Maths
- Top 7 Career Options After PCB
- Best Career Options for Commerce
- Career Options After 12th CS
- Top 10 Career Options After 10th
- 8 Best Career Options After BA
- Projects and Academic Pursuits
- 17 Exciting Final Year Projects
- Top 12 Commerce Project Topics
- Top 13 BCA Project Ideas
- Career Options After 12th Science
- Top 15 CS Jobs in India
- 12 Best Career Options After M.Com
- 9 Best Career Options After B.Sc
- 7 Best Career Options After BCA
- 22 Best Career Options After MCA
- 16 Top Career Options After CE
- Courses and Certifications
- 10 Best Job-Oriented Courses
- Best Online Computer Courses
- Top 15 Trending Online Courses
- Top 19 High Salary Certificate Courses
- 21 Best Programming Courses for Jobs
- What is SGPA? Convert to CGPA
- GPA to Percentage Calculator
- Highest Salary Engineering Stream
- 15 Top Career Options After Engineering
- 6 Top Career Options After BBA
- Job Market and Interview Preparation
- Why Should You Be Hired: 5 Answers
- Top 10 Future Career Options
- Top 15 Highest Paid IT Jobs India
- 5 Common Guesstimate Interview Q&A
- Average CEO Salary: Top Paid CEOs
- Career Options in Political Science
- Top 15 Highest Paying Non-IT Jobs
- Cover Letter Examples for Jobs
- Top 5 Highest Paying Freelance Jobs
- Top 10 Highest Paying Companies India
- Career Options and Paths After MBA
- 20 Best Careers After B.Com
- Career Options After MBA Marketing
- Top 14 Careers After MBA In HR
- Top 10 Highest Paying HR Jobs India
- How to Become an Investment Banker
- Career Options After MBA - High Paying
- Scope of MBA in Operations Management
- Best MBA for Working Professionals India
- MBA After BA - Is It Right For You?
- Best Online MBA Courses India
- MBA Project Ideas and Topics
- 11 Exciting MBA HR Project Ideas
- Top 15 MBA Project Ideas
- 18 Exciting MBA Marketing Projects
- MBA Project Ideas: Consumer Behavior
- What is Brand Management?
- What is Holistic Marketing?
- What is Green Marketing?
- Intro to Organizational Behavior Model
- Tech Skills Every MBA Should Learn
- Most Demanding Short Term Courses MBA
- MBA Salary, Resume, and Skills
- MBA Salary in India
- HR Salary in India
- Investment Banker Salary India
- MBA Resume Samples
- Sample SOP for MBA
- Sample SOP for Internship
- 7 Ways MBA Helps Your Career
- Must-have Skills in Sales Career
- 8 Skills MBA Helps You Improve
- Top 20+ SAP FICO Interview Q&A
- MBA Specializations and Comparative Guides
- Why MBA After B.Tech? 5 Reasons
- How to Answer 'Why MBA After Engineering?'
- Why MBA in Finance
- MBA After BSc: 10 Reasons
- Which MBA Specialization to choose?
- Top 10 MBA Specializations
- MBA vs Masters: Which to Choose?
- Benefits of MBA After CA
- 5 Steps to Management Consultant
- 37 Must-Read HR Interview Q&A
- Fundamentals and Theories of Management
- What is Management? Objectives & Functions
- Nature and Scope of Management
- Decision Making in Management
- Management Process: Definition & Functions
- Importance of Management
- What are Motivation Theories?
- Tools of Financial Statement Analysis
- Negotiation Skills: Definition & Benefits
- Career Development in HRM
- Top 20 Must-Have HRM Policies
- Project and Supply Chain Management
- Top 20 Project Management Case Studies
- 10 Innovative Supply Chain Projects
- Latest Management Project Topics
- 10 Project Management Project Ideas
- 6 Types of Supply Chain Models
- Top 10 Advantages of SCM
- Top 10 Supply Chain Books
- What is Project Description?
- Top 10 Project Management Companies
- Best Project Management Courses Online
- Salaries and Career Paths in Management
- Project Manager Salary in India
- Average Product Manager Salary India
- Supply Chain Management Salary India
- Salary After BBA in India
- PGDM Salary in India
- Top 7 Career Options in Management
- CSPO Certification Cost
- Why Choose Product Management?
- Product Management in Pharma
- Product Design in Operations Management
- Industry-Specific Management and Case Studies
- Amazon Business Case Study
- Service Delivery Manager Job
- Product Management Examples
- Product Management in Automobiles
- Product Management in Banking
- Sample SOP for Business Management
- Video Game Design Components
- Top 5 Business Courses India
- Free Management Online Course
- SCM Interview Q&A
- Fundamentals and Types of Law
- Acceptance in Contract Law
- Offer in Contract Law
- 9 Types of Evidence
- Types of Law in India
- Introduction to Contract Law
- Negotiable Instrument Act
- Corporate Tax Basics
- Intellectual Property Law
- Workmen Compensation Explained
- Lawyer vs Advocate Difference
- Law Education and Courses
- LLM Subjects & Syllabus
- Corporate Law Subjects
- LLM Course Duration
- Top 10 Online LLM Courses
- Online LLM Degree
- Step-by-Step Guide to Studying Law
- Top 5 Law Books to Read
- Why Legal Studies?
- Pursuing a Career in Law
- How to Become Lawyer in India
- Career Options and Salaries in Law
- Career Options in Law India
- Corporate Lawyer Salary India
- How To Become a Corporate Lawyer
- Career in Law: Starting, Salary
- Career Opportunities: Corporate Law
- Business Lawyer: Role & Salary Info
- Average Lawyer Salary India
- Top Career Options for Lawyers
- Types of Lawyers in India
- Steps to Become SC Lawyer in India
- Tutorials
- Software Tutorials
- C Tutorials
- Recursion in C: Fibonacci Series
- Checking String Palindromes in C
- Prime Number Program in C
- Implementing Square Root in C
- Matrix Multiplication in C
- Understanding Double Data Type
- Factorial of a Number in C
- Structure of a C Program
- Building a Calculator Program in C
- Compiling C Programs on Linux
- Java Tutorials
- Handling String Input in Java
- Determining Even and Odd Numbers
- Prime Number Checker
- Sorting a String
- User-Defined Exceptions
- Understanding the Thread Life Cycle
- Swapping Two Numbers
- Using Final Classes
- Area of a Triangle
- Skills
- Explore Skills
- Management Skills
- Software Engineering
- JavaScript
- Data Structure
- React.js
- Core Java
- Node.js
- Blockchain
- SQL
- Full stack development
- Devops
- NFT
- BigData
- Cyber Security
- Cloud Computing
- Database Design with MySQL
- Cryptocurrency
- Python
- Digital Marketings
- Advertising
- Influencer Marketing
- Performance Marketing
- Search Engine Marketing
- Email Marketing
- Content Marketing
- Social Media Marketing
- Display Advertising
- Marketing Analytics
- Web Analytics
- Affiliate Marketing
- MBA
- MBA in Finance
- MBA in HR
- MBA in Marketing
- MBA in Business Analytics
- MBA in Operations Management
- MBA in International Business
- MBA in Information Technology
- MBA in Healthcare Management
- MBA In General Management
- MBA in Agriculture
- MBA in Supply Chain Management
- MBA in Entrepreneurship
- MBA in Project Management
- Management Program
- Consumer Behaviour
- Supply Chain Management
- Financial Analytics
- Introduction to Fintech
- Introduction to HR Analytics
- Fundamentals of Communication
- Art of Effective Communication
- Introduction to Research Methodology
- Mastering Sales Technique
- Business Communication
- Fundamentals of Journalism
- Economics Masterclass
- Free Courses
- Home
- Blog
- Software Development
- Doubly Linked List Implementation in C and Java: A Comprehensive Guide
Doubly Linked List Implementation in C and Java: A Comprehensive Guide
Updated on Mar 20, 2025 | 21 min read | 1.3k views
Share:
Table of Contents
- Understanding the Doubly Linked List Implementation: How Does It Really Work?
- Step-by-Step Guide to Generate a Doubly Linked List in C
- How to Create and Display a Doubly Linked List in Java? A Beginner’s Guide
- Why Choose a Doubly Linked List? Exploring Its Pros and Cons
- Exploring Real-World Applications with Doubly Linked List Examples
- How Can upGrad Improve Your Knowledge of C and Java Programming?
Doubly Linked Lists are a key data structure in computer science, helping solve problems that require efficient insertion and deletion operations. Unlike singly linked lists, a doubly linked list allows traversal in both directions, making it more versatile in scenarios where both forward and backward navigation are needed.
For example, web browsers use doubly linked lists to navigate through history, allowing users to move both forwards and backwards through the pages they've visited. Similarly, multimedia applications use this data structure to manage playlists, where you can move seamlessly through songs in both directions.
In this blog, you’ll learn Doubly Linked List implementation in both C and Java. You’ll explore its core operations, practical examples, and the advantages of using this structure in real-world applications.
Understanding the Doubly Linked List Implementation: How Does It Really Work?
A doubly linked list is a type of linked list where each node contains three parts: the data, a pointer to the next node, and a pointer to the previous node.
Here are its key features:
- Each node holds the actual data you want to store (like a number or a string).
- The next pointer points to the next node in the list.
- The prev pointer points to the previous node, which makes it different from a singly linked list, where nodes only point to the next node.
This structure enables bidirectional traversal, allowing you to move through the list from both ends.
Here are some core operations that you can perform using doubly linked list:
1. Traversing a Doubly Linked List: Traversing a doubly linked list is simple. You start at the head node and move forward using the next pointer. Want to go backward? Start at the tail and use the prev pointer. This bidirectional navigation makes it easier to explore data in both directions.
Imagine you have the following doubly linked list:
Head <-> 10 <-> 20 <-> 30 <-> Tail
Forward Traversal: Start at the head (10). Follow the next pointers:
- First node: 10 → Next node: 20 → Next node: 30
- End at the tail.
Backward Traversal: Start at the tail (30). Follow the prev pointers:
- First node: 30 ← Previous node: 20 ← Previous node: 10
- End at the head.
You can easily move through the list in both directions using the next and prev pointers.
2. Finding the Length of a Doubly Linked List: Counting the number of nodes in a doubly linked list is straightforward. You start at the head and traverse through each node, counting as you go. Since there’s no skipping, every node gets counted until you hit the end of the list.
Let’s say the doubly linked list is:
Head <-> 5 <-> 10 <-> 15 <-> Tail
To find the length, start at the head and count each node as you go through the list:
- Start at head (5), count it as 1.
- Move to the next node (10), count it as 2.
- Move to the next node (15), count it as 3.
- End at the tail.
So, the length of the list is 3. You’ve visited 3 nodes in total.
3. Inserting and Deleting Nodes: Insertion is quick! You can insert at the beginning, the end, or in the middle. When inserting in the middle, you only need to adjust the prev and next pointers of the neighboring nodes. Deleting nodes works similarly. Just make sure to update the surrounding nodes' pointers when removing a node to keep the list intact.
Imagine you have this list:
Head <-> 10 <-> 20 <-> Tail
Now, you want to insert 5 at the beginning:
- Create a new node for 5.
- Set its next pointer to the current head (10).
- Set the prev pointer of the current head (10) to the new node (5).
- Update the head to point to the new node (5).
After insertion:
Head <-> 5 <-> 10 <-> 20 <-> Tail
Now, let's delete the last node (20):
- Start at the head and find the last node.
- Set the prev pointer of the tail (20) to null.
- Update the tail to the previous node (10).
After deletion:
Head <-> 5 <-> 10 <-> Tail
4. Handling Edge Cases: If the list is empty, the head and tail pointers are null, meaning there’s nothing to traverse. If there’s just one node and it’s deleted, both the head and tail become null. It’s crucial to handle this to avoid any dangling references.
An empty list looks like this:
Head -> null
Tail -> null
In this case, there are no nodes to traverse or manipulate. Both the head and tail are null.
Consider this list with just one node:
Head <-> 10 <-> Tail
If you delete the node:
- Set both head and tail to null because there are no more nodes.
- The list is now empty:
Head -> null
Tail -> null
These simple examples should make it clearer how the core operations work in a doubly linked list.
With these core operations, a doubly linked list becomes an efficient and flexible data structure, offering more functionality than a singly linked list while requiring just a bit more memory for the extra pointer.
Also Read: What are Data Structures & Algorithm
Now that you understand the basic principles of a doubly linked list implementation, let’s dive into how to implement it in C.
Step-by-Step Guide to Generate a Doubly Linked List in C
Implementing a doubly linked list in C offers deep insights into low-level memory management. In C, you manually allocate and deallocate memory using malloc and free, providing you with fine-grained control over resource usage and performance.
Unlike Java, which relies on garbage collection, C requires explicit management of both next and prev pointers. While Java simplifies memory handling, it introduces overhead due to garbage collection, which may not always be ideal for high-performance or real-time systems.
This hands-on approach in C allows for better control over memory and is why C is preferred in systems programming and embedded systems.
Step 1: Creating the Node Structure
A doubly linked list node holds three components: data, next pointer, and prev pointer. Here’s how you define it in C:
struct Node {
int data; // Data stored in the node
struct Node* next; // Pointer to the next node
struct Node* prev; // Pointer to the previous node
};
Step 2: Building the List: Insertion
Now, let’s go over how to insert nodes at the beginning, end, and specific position in the list.
To insert a node at the beginning, you:
- Allocate memory for the new node.
- Set the new node’s next pointer to the current head.
- Set the current head’s prev pointer to the new node.
- Update the head to point to the new node.
void insertAtBeginning(struct Node** head, int newData) {
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->data = newData;
newNode->next = *head;
newNode->prev = NULL;
if (*head != NULL) {
(*head)->prev = newNode;
}
*head = newNode;
}
For insertion at the end:
- Traverse the list to find the last node.
- Set the last node’s next pointer to the new node.
- Set the new node’s prev pointer to the last node.
- The new node’s next pointer is set to NULL.
void insertAtEnd(struct Node** head, int newData) {
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
struct Node* last = *head;
newNode->data = newData;
newNode->next = NULL;
if (*head == NULL) {
newNode->prev = NULL;
*head = newNode;
return;
}
while (last->next != NULL) {
last = last->next;
}
last->next = newNode;
newNode->prev = last;
}
To insert at a given position:
- Traverse the list to reach the node before the specified position.
- Update the next and prev pointers accordingly.
void insertAtPosition(struct Node** head, int newData, int position) {
if (position == 0) {
insertAtBeginning(head, newData);
return;
}
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
struct Node* temp = *head;
newNode->data = newData;
for (int i = 0; temp != NULL && i < position - 1; i++) {
temp = temp->next;
}
if (temp == NULL) {
printf("Position out of bounds\n");
return;
}
newNode->next = temp->next;
newNode->prev = temp;
if (temp->next != NULL) {
temp->next->prev = newNode;
}
temp->next = newNode;
}
Step 3: Displaying the List: Traversing and Printing
After inserting nodes, you can traverse and print the list. We’ll show both forward and backward traversal.
The forward traversal prints the list starting from the head, moving to the next node until the end.
void displayForward(struct Node* head) {
struct Node* temp = head;
while (temp != NULL) {
printf("%d <-> ", temp->data);
temp = temp->next;
}
printf("NULL\n");
}
For backward traversal, start at the tail of the list and move backward using the prev pointers.
void displayBackward(struct Node* head) {
if (head == NULL) return;
struct Node* temp = head;
while (temp->next != NULL) {
temp = temp->next;
}
while (temp != NULL) {
printf("%d <-> ", temp->data);
temp = temp->prev;
}
printf("NULL\n");
}
Step 4: Deleting Nodes
Deleting nodes involves updating the surrounding nodes' pointers to maintain the list integrity.
This function deletes the first node and updates the head:
void deleteFromBeginning(struct Node** head) {
if (*head == NULL) return;
struct Node* temp = *head;
*head = (*head)->next;
if (*head != NULL) {
(*head)->prev = NULL;
}
free(temp);
}
For deleting the last node:
- Traverse to the last node.
- Set the second last node’s next pointer to NULL.
void deleteFromEnd(struct Node** head) {
if (*head == NULL) return;
struct Node* last = *head;
while (last->next != NULL) {
last = last->next;
}
if (last->prev != NULL) {
last->prev->next = NULL;
} else {
*head = NULL;
}
free(last);
}
Complete C Code Doubly Linked List Example
Here’s the full program combining all the above steps, demonstrating the doubly linked list operations.
#include <stdio.h>
#include <stdlib.h>
struct Node {
int data;
struct Node* next;
struct Node* prev;
};
// Function declarations
void insertAtBeginning(struct Node** head, int newData);
void insertAtEnd(struct Node** head, int newData);
void insertAtPosition(struct Node** head, int newData, int position);
void displayForward(struct Node* head);
void displayBackward(struct Node* head);
void deleteFromBeginning(struct Node** head);
void deleteFromEnd(struct Node** head);
int main() {
struct Node* head = NULL;
insertAtBeginning(&head, 10);
insertAtEnd(&head, 20);
insertAtPosition(&head, 15, 1);
printf("List in Forward Order:\n");
displayForward(head);
printf("List in Backward Order:\n");
displayBackward(head);
deleteFromEnd(&head);
printf("After Deleting from End:\n");
displayForward(head);
return 0;
}
Explanation: This program demonstrates how to insert nodes at the beginning, end, and specific positions. It also shows how to display the list both forwards and backwards and delete nodes from the end.
Expected Output:
List in Forward Order:
15 <-> 10 <-> 20 <-> NULL
List in Backward Order:
20 <-> 10 <-> 15 <-> NULL
After Deleting from End:
15 <-> 10 <-> NULL
By following these steps, you can easily implement a fully functional doubly linked list in C. The operations for insertion, traversal, and deletion provide flexibility and efficiency in managing a dynamic set of elements.
Also Read: 29 C Programming Projects to Try in 2025 With Source Code
With a solid understanding of doubly linked list implementation in C, let’s now explore how to build a similar structure in Java.
How to Create and Display a Doubly Linked List in Java? A Beginner’s Guide
Creating a Doubly Linked List in Java involves defining a node class with both forward and backward pointers, followed by building a linked list class to handle insertion, deletion, and traversal.
Unlike C, Java simplifies memory management through garbage collection, freeing developers from manual memory allocation. However, this can introduce performance overhead, particularly in real-time systems, where fine-grained control over memory is crucial.
Despite this, Java's object-oriented structure makes it easier to implement and maintain complex data structures like linked lists.
Let’s go through the steps to build and display a doubly linked list in Java.
Step 1: Defining the Node Class
First, you need to define the Node class. Here’s how you can define the Node class in Java:
class Node {
int data;
Node next;
Node prev;
// Constructor to create a new node
public Node(int data) {
this.data = data;
this.next = null;
this.prev = null;
}
}
The Node class has three components: data, next, and prev. The constructor initializes the data of the node and sets both the next and prev pointers to null.
Step 2: Setting Up the DoublyLinkedList Class
After defining the Node class, you can now move on to creating the DoublyLinkedList class to manage the nodes. This class will contain the following methods:
- Insert: Insert nodes at the beginning, end, or a specific position.
- Delete: Remove nodes from the beginning, end, or a specific position.
- Display: Traverse the list and display the elements in both forward and backward directions.
class DoublyLinkedList {
Node head; // Head of the list
// Constructor to create an empty list
public DoublyLinkedList() {
this.head = null;
}
}
The DoublyLinkedList class has a head pointer to the first node in the list. Initially, it’s set to null.
Step 3: Implementing Insertion and Deletion
Now, let’s implement the methods to insert and delete nodes in the list. This includes:
- Inserting at the beginning.
- Inserting at the end.
- Inserting at a specific position.
- Deleting from the beginning and end.
Insertion at the Beginning:
public void insertAtBeginning(int data) {
Node newNode = new Node(data);
newNode.next = head; // Link new node to the current head
if (head != null) {
head.prev = newNode; // Set prev pointer of the old head to the new node
}
head = newNode; // Move head to point to the new node
}
This method inserts a node at the beginning by adjusting the head pointer and linking the new node to the current head.
Insertion at the End:
public void insertAtEnd(int data) {
Node newNode = new Node(data);
if (head == null) {
head = newNode; // If the list is empty, make the new node the head
return;
}
Node last = head;
while (last.next != null) {
last = last.next; // Traverse to the last node
}
last.next = newNode;
newNode.prev = last; // Set prev of new node to the last node
}
If the list is empty, the new node becomes the head. Otherwise, we traverse to the last node and link it to the new node.
Insertion at a Specific Position:
public void insertAtPosition(int data, int position) {
if (position == 0) {
insertAtBeginning(data);
return;
}
Node newNode = new Node(data);
Node temp = head;
for (int i = 0; temp != null && i < position - 1; i++) {
temp = temp.next; // Traverse to the node before the desired position
}
if (temp == null) {
System.out.println("Position out of bounds");
return;
}
newNode.next = temp.next; // Link the new node to the next node
newNode.prev = temp; // Link the new node to the previous node
if (temp.next != null) {
temp.next.prev = newNode; // Update the previous pointer of the next node
}
temp.next = newNode; // Update the next pointer of the previous node
}
If the position is 0, it calls the insertAtBeginning method. Otherwise, it traverses to the node before the desired position and adjusts the pointers to insert the new node.
Deletion from the Beginning:
public void deleteFromBeginning() {
if (head == null) return; // If the list is empty, do nothing
head = head.next; // Move the head pointer to the next node
if (head != null) {
head.prev = null; // Set the previous pointer of the new head to null
}
}
This method removes the first node by updating the head pointer to point to the next node and adjusting the prev pointer of the new head.
Deletion from the End:
public void deleteFromEnd() {
if (head == null) return; // If the list is empty, do nothing
Node last = head;
while (last.next != null) {
last = last.next; // Traverse to the last node
}
if (last.prev != null) {
last.prev.next = null; // Set the next pointer of the second last node to null
} else {
head = null; // If the list has only one node, set head to null
}
}
This method traverses the list to find the last node and removes it by adjusting the next pointer of the second-last node.
Step 4: Traversal and Display
Let’s implement methods to traverse and display the list forward and backward.
Forward Traversal:
public void displayForward() {
Node temp = head;
while (temp != null) {
System.out.print(temp.data + " <-> ");
temp = temp.next;
}
System.out.println("NULL");
}
This method starts at the head and moves forward through the list, printing the data of each node.
Backward Traversal:
public void displayBackward() {
if (head == null) return; // If the list is empty, do nothing
Node temp = head;
while (temp.next != null) {
temp = temp.next; // Traverse to the last node
}
while (temp != null) {
System.out.print(temp.data + " <-> ");
temp = temp.prev; // Move to the previous node
}
System.out.println("NULL");
}
This method traverses the list backward, starting at the tail and moving to the previous node.
Complete Java Code Doubly Linked List Example
Now, let’s put everything together with a complete Java example that demonstrates how to build and manipulate a doubly linked list:
class Node {
int data;
Node next;
Node prev;
public Node(int data) {
this.data = data;
this.next = null;
this.prev = null;
}
}
class DoublyLinkedList {
Node head;
public DoublyLinkedList() {
this.head = null;
}
// Insert methods (insert at beginning, end, position)
public void insertAtBeginning(int data) { /* ... */ }
public void insertAtEnd(int data) { /* ... */ }
public void insertAtPosition(int data, int position) { /* ... */ }
// Delete methods (delete from beginning, end)
public void deleteFromBeginning() { /* ... */ }
public void deleteFromEnd() { /* ... */ }
// Display methods (forward and backward)
public void displayForward() { /* ... */ }
public void displayBackward() { /* ... */ }
public static void main(String[] args) {
DoublyLinkedList list = new DoublyLinkedList();
// Inserting nodes
list.insertAtBeginning(10);
list.insertAtEnd(20);
list.insertAtPosition(15, 1);
System.out.println("List in Forward Order:");
list.displayForward();
System.out.println("List in Backward Order:");
list.displayBackward();
// Deleting from the end
list.deleteFromEnd();
System.out.println("After Deleting from End:");
list.displayForward();
}
}
In this Java implementation of a Doubly Linked List, the Node class contains data, next, and prev references. The DoublyLinkedList class handles insertion, deletion, and traversal, with Java using object references instead of manual pointers. The main method demonstrates these operations.
Unlike C, Java handles memory management automatically through garbage collection, simplifying the implementation. This code highlights Java's object-oriented approach and memory management for creating a doubly linked list.
Expected Output:
List in Forward Order:
10 <-> 15 <-> 20 <-> NULL
List in Backward Order:
20 <-> 15 <-> 10 <-> NULL
After Deleting from End:
10 <-> 15 <-> NULL
By mastering these techniques, you’ll be well-equipped to implement and optimize doubly linked lists in your Java projects.
Also Read: Data Structures in Javascript Explained: Importance, Types & Advantages
With a clear understanding of Doubly Linked List implementation in Java, let’s dive deeper into how exactly it will benefit you as a programmer.
Why Choose a Doubly Linked List? Exploring Its Pros and Cons
A Doubly Linked List is a powerful data structure, but like any tool, it comes with its set of advantages and disadvantages. When deciding whether to use a doubly linked list, it's essential to weigh these factors and consider the specific use cases where this structure shines or falls short.
When to Use a Doubly Linked List:
- When you need bidirectional traversal. This is helpful in applications like web browsers (forward and backward navigation) or music players (navigate both ways in a playlist).
- When your operations require efficient deletion or insertion at both ends of the list.
- In real-time applications where performance improvements in deletion or insertion are critical (e.g., memory management systems, cache management).
When Not to Use a Doubly Linked List:
- When memory efficiency is a concern. If you don’t need bidirectional traversal, the additional prev pointer in each node adds unnecessary memory overhead.
- When simpler data structures like singly linked lists can handle your needs. If you don’t require backward traversal or fast deletions from arbitrary positions, a singly linked list is more space-efficient and easier to implement.
Here’s a comparison of the pros and cons of a doubly linked list:
Advantages |
Disadvantages |
You can traverse the list both forwards and backwards. | Requires extra space for the prev pointer. |
Deleting a node is faster because you have access to both previous and next pointers. | More complicated than singly linked lists, especially when handling edge cases (like empty or single-node lists). |
Easier insertion at both ends and at specific positions in the list. | Slightly slower than singly linked lists due to the increased number of pointers and extra memory overhead. |
So, doubly linked lists offer powerful advantages in terms of flexibility and efficiency for certain operations. However, they come at the cost of increased memory usage and implementation complexity.
Also Read: Data Structures & Algorithm in Python: Everything You Need to Know
Now that you know when to use Doubly Linked Lists, it’s time to dive into the real-world applications so you understand them better.
Exploring Real-World Applications with Doubly Linked List Examples
Doubly linked lists are powerful data structures that provide efficient bidirectional navigation, fast insertion, and deletion at both ends. These features make them ideal for situations where quick, flexible modifications to data are needed.
In real-world applications, doubly linked lists are often used in systems requiring dynamic memory management, history tracking, or efficient data traversal.
Let’s explore how this data structure is leveraged across different domains.
1. Music/Video Players (Playlist Management)
In media players like Spotify or VLC, doubly linked lists are used to manage playlists. This allows users to easily navigate through songs or videos, moving backwards and forwards in the playlist.
For example, when a user clicks "next" or "previous," the player moves between nodes in the list, providing flexibility and efficient playback control. This structure is ideal for scenarios where bidirectional traversal is needed for smooth navigation.
2. Memory Management Systems
In older operating systems, doubly linked lists were employed in memory management to track free memory blocks in a heap. The structure allowed efficient allocation and deallocation by moving forward or backward through memory blocks.
However, modern operating systems often use more advanced systems like buddy systems or free lists. These offer better performance and handle memory fragmentation more effectively, making doubly linked lists less common today.
3. Undo/Redo Functionality
In software like word processors or graphic design tools, doubly linked lists store a history of user actions, enabling efficient undo and redo operations. Each action is represented as a node in the list, allowing users to move back and forth through their history of changes.
This bidirectional traversal ensures that users can easily navigate through edits, even in complex workflows with multiple steps.
4. Operating System Process Scheduling
In operating systems, doubly linked lists are used to manage process scheduling. Processes are stored as nodes, with the ability to quickly switch between them using forward and backward navigation. This allows OS schedulers to prioritize or pause tasks efficiently.
For example, during multitasking, processes can be scheduled in a way that prioritizes critical tasks while allowing easy transitions to background tasks, all managed dynamically by the doubly linked list structure.
5. Job Scheduling in Real-Time Systems
In real-time systems, such as telecommunications or industrial machinery, doubly linked lists help manage tasks or jobs that need to be executed at specific intervals. The structure allows for efficient scheduling and rescheduling of tasks, where new jobs can be added or completed jobs can be removed by navigating through the list.
This capability is crucial for systems that require precise timing and management of jobs in both directions.
6. Navigation Systems (GPS)
In GPS navigation systems, doubly linked lists are used to store routes and waypoints. As users navigate, the system allows for backward and forward navigation through waypoints, helping them adjust their path easily.
If a user needs to retrace steps or take a different route, the doubly linked list allows for smooth transitions between previous and next points, ensuring efficient pathfinding.
7. Database Record Management
Doubly linked lists are used in database indices to store references to records, enabling efficient insertion, deletion, and bidirectional traversal of records. For example, in a transactional database, as new records are added, they can be quickly accessed or removed from any point in the list, improving query performance.
This flexibility makes doubly linked lists ideal for databases with frequent updates and complex queries.
8. Browser Tab Management
Web browsers like Chrome or Firefox use doubly linked lists to manage open tabs. This allows users to efficiently switch between tabs and navigate back and forth through their browsing history.
When users press the "back" or "forward" buttons, the browser uses the doubly linked list to traverse through the history of visited pages, making the browsing experience smoother and more responsive.
These unique applications show how doubly linked lists enable dynamic, efficient management of data where both forward and backward navigation or operations are key to system performance.
Also Read: 20 Most Popular Programming Languages in 2025
Now that you’re familiar with the Doubly Linked List implementation and usage, let’s explore how upGrad can take your learning journey forward.
How Can upGrad Improve Your Knowledge of C and Java Programming?
With your strong foundation in Doubly Linked Lists, you’re ready to advance your programming skills with upGrad’s advanced courses. Learn advanced techniques in data structures, algorithms, and practical applications to accelerate your career in software development.
Through hands-on projects, you’ll apply these concepts to solve complex problems. You will be able to efficiently manage data structures like doubly linked lists and build high-performance applications.
Here are some relevant courses you can explore:
- Java Object-oriented Programming
- JavaScript Basics from Scratch
- Master of Science in AI and Data Science
- Best Full Stack Developer Bootcamp
- Master of Design in User Experience
If you're unsure about the next step in your learning journey, you can contact upGrad’s personalized career counseling for guidance on choosing the best path tailored to your goals. You can also visit your nearest upGrad center and start hands-on training today!
Boost your career with our popular Software Engineering courses, offering hands-on training and expert guidance to turn you into a skilled software developer.
Explore our Popular Software Engineering Courses
Master in-demand Software Development skills like coding, system design, DevOps, and agile methodologies to excel in today’s competitive tech industry.
In-Demand Software Development Skills
Stay informed with our widely-read Software Development articles, covering everything from coding techniques to the latest advancements in software engineering.
Read our Popular Articles related to Software
Frequently Asked Questions (FAQs)
1. How does a doubly linked list improve performance in web browser history management?
2. Why is a doubly linked list preferred for managing playlists in music or video players?
3. What challenges do developers face when implementing undo/redo functionality using doubly linked lists?
4. How can doubly linked lists be used in operating system process scheduling?
5. What’s the advantage of using a doubly linked list for job scheduling in real-time systems?
6. Why might a doubly linked list be inefficient for smaller, static datasets?
7. How can a doubly linked list help with memory management in operating systems?
8. In database systems, how do doubly linked lists improve index management?
9. What performance issues might arise when using a doubly linked list in large-scale applications?
10. How are doubly linked lists useful in real-time data structures for navigation systems?
11. What are some limitations of using doubly linked lists in real-time applications?
Get Free Consultation
By submitting, I accept the T&C and
Privacy Policy
India’s #1 Tech University
Executive PG Certification in AI-Powered Full Stack Development
77%
seats filled
Top Resources