How is a double linked list implemented in the C programming language?
To implement a data structure of a doubly linked list, you can follow the steps below:
- Create a node structure. Each node should have two pointers, one pointing to the previous node and one pointing to the next node. Additionally, the node should also contain a variable to store data.
typedef struct Node {
int data;
struct Node* prev;
struct Node* next;
} Node;
- Define a struct for a linked list. The linked list struct should include pointers for the head node and tail node.
typedef struct LinkedList {
Node* head;
Node* tail;
} LinkedList;
- Implement a constructor. The constructor is used to create an empty list.
void initLinkedList(LinkedList* list) {
list->head = NULL;
list->tail = NULL;
}
- Create a function to insert nodes. The insertion function should consider both the head node and the tail node.
void insertNode(LinkedList* list, int data) {
Node* newNode = (Node*)malloc(sizeof(Node));
newNode->data = data;
newNode->prev = NULL;
newNode->next = NULL;
if (list->head == NULL) {
list->head = newNode;
list->tail = newNode;
} else {
newNode->prev = list->tail;
list->tail->next = newNode;
list->tail = newNode;
}
}
- Create a function that removes a node. The delete function should consider the position of the node in the linked list.
void deleteNode(LinkedList* list, int data) {
Node* current = list->head;
while (current != NULL) {
if (current->data == data) {
if (current->prev != NULL) {
current->prev->next = current->next;
} else {
list->head = current->next;
}
if (current->next != NULL) {
current->next->prev = current->prev;
} else {
list->tail = current->prev;
}
free(current);
return;
}
current = current->next;
}
}
- Create a function to print a linked list.
void printLinkedList(LinkedList* list) {
Node* current = list->head;
while (current != NULL) {
printf("%d ", current->data);
current = current->next;
}
printf("\n");
}
After completing the above steps, you can use these functions to create and manipulate a doubly linked list.