Doubly Linked List Program in JavaDoubly linked list programs are very complex programs to understand because the node of the doubly linked list contains two fields, previous and next. In C and C++, it is very easy to maintain a doubly linked list using pointers, but in Java, there is no concept of pointer that makes its construction a little bit tricky. A doubly linked list program can be of creating a doubly-linked list, inserting a node, or deleting a node. Let's understand some basic programs of doubly linked list: Creating a doubly linked listFor creating a node, we have to create a class for creating a Node type. The class contains three properties, i.e., data, prev, and next. The data can be of int, String, or float and prev and next are of the Node type. The user stores the information, and prev and next contain the previous and next nodes of the doubly linked list. In the given program, each line of code is defined through comments so that you can understand the code easily. CreateDoublyLinkedList.java Output: Inserting a Node into a doubly-linked listIn the doubly linked list, a node can be inserted into one of the following ways:
We will understand all these ways by creating their programs one by one. Insert a node in the beginningIn the CreateDoublyLinkedList example, the newly created node is added in the last of the doubly linked list. When we need to add a node at the beginning of the list, we need to change the value of the head node and the node which was pointed by that head. So, we will use the same example which we create above. We only add a method to that program for adding a node at the beginning of the list. AddNodeInBeginning.java Output: Insert a node at the endWe can add a node at the end of the list too. In the CreateDoublyLinkedList program, each newly created node ad at the end of the list. So, we can say that the code of inserting a node at the end is already discussed before. But to make it more specific, we have given another example in which we create a separate method for adding a node. AddNodeAtEnd.java Output: Insert a node at the specified positionIn order to create a program for adding a node at the specified position, we have to focus on the following four cases:
In the given code, we create separate methods for each case and try to make it as simple as possible. AddNodeAtSpecifiedLocation.java Output: Deleting a Node from a doubly linked listFor deleting a node, three cases are possible:
In the given program, we have created three methods for these three different cases. Each line of code is described through comments in the program to make it easy to understand. DeleteNodeFromList.java Output: Next TopicJava 12 |
We provides tutorials and interview questions of all technology like java tutorial, android, java frameworks
G-13, 2nd Floor, Sec-3, Noida, UP, 201301, India