We know that, in a singly linked list every elements (node) has a pointer to its next element (node) in the sequence. Hence, if we want to traverse the singly linked list then we can traverse in only one direction. We cannot traverse back in the singly linked list.
But now we want to traverse in the both direction i.e. in forward direction and backward direction. We can solve this kind of problem using doubly linked list.
“Doubly linked list is a sequence of nodes in which every node has a link to its previous node as well as next node in the sequence.”
So, if we want to traverse forward in the linked list then we can use next field and if we want to traverse backward in the linked list then we can use previous field.
Example–
Also read: Singly Linked List
Also read: Circular Linked List
Also read: Circular Doubly Linked List
Declaring the Doubly Linked List:
We know that, we can implement a doubly linked list using self referential structure. Because self referential structure is a structure that contains a data field and a prev_pointer field that points to the previous node in the list and a next_pointer field that points to the next node in the list.
This is how you can use the above definition to create every node in the doubly linked list. The data field stores an integer and *prev_link is a pointer that holds the address of the prev node in the linked list and *next_link is a pointer that holds the address of the next node in the linked list.
Traversing a Doubly Linked List:
In the below program I will show you how to create and traverse the doubly linked list in both direction. The above program have three functions-
- create_list() : to create the linked list.
- trav_f() : to traverse the linked list in forward direction.
- trav_b() : to traverse the linked list in backward direction.
Example–
Output–
This is how our doubly linked list looked like:
If you want to understand the above program then click here!
Be First to Comment