![]() |
VOOZH | about |
A doubly linked list is a type of linked list in which each node contains a pointer to both the next node and the previous node. This allows traversal in both forward and backward directions. Each node in a doubly linked list stores data, a pointer to the next node, and a pointer to the previous node.
In this article, we will learn how to create/implement a doubly linked list in C.
Example
Input: Create Doubly Linked List with 1 2 3 4
Output: head = [1] <-> [2] <-> [3] <-> [4] <-> NULL
Explanation: The doubly linked list is created with nodes containing values 1, 2, 3, and 4.Input: Create Doubly Linked List with 10 20 30
Output: head = [10] <-> [20] <-> [30] <-> NULL
Explanation: The doubly linked list is created with nodes containing values 10, 20, and 30.
In C, we can represent a doubly linked list node using the struct type, which allows grouping multiple data types in a single variable. Each node in a doubly linked list should have pointers to both the next node and the previous node along with the data field. We can then use a pointer to the head node to manage the entire list.
Below is an example structure that represents a doubly linked list node:
We can create a doubly linked list node using dynamic memory allocation and structure pointers. Dynamic allocation is preferred to utilize the full flexibility of the doubly linked list.
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));If you prefer to avoid repeatedly writing struct Node*, you can use typedef to define an alias:
Then we can create the node as:
Node* node2 = (Node*)malloc(sizeof(Node));After creating nodes, link them by setting the next and prev pointers accordingly. The prev pointer of each node should point to its previous node, and the next pointer should point to the next node in the list. The first node's prev pointer and the last node's next pointer should be set to NULL.
We can also use a utility function like createNode() that creates and initialize the node members to either provided or default values. This will ease the process of creating and even linking node.
The following example implements the approach to create a doubly linked list in C:
Doubly Linked List: 10 20 30
Time Complexity: O(N) where N is the total number of nodes in the linked list.
Auxiliary Space: O(N)
In this article, we have discussed how to create a doubly linked list in C. We have covered the representation of the doubly linked list node, the process of creating nodes, linking them, and traversing the list. Doubly linked lists provide the flexibility to traverse in both directions, which can be particularly useful in various applications.
Feel free to modify the code according to your specific needs or requirements!