Algorithms-and-Data-Structures/C-Doubly-Linked-List/main.c
2024-05-02 20:14:36 +01:00

70 lines
1.5 KiB
C

#include <stdio.h>
#include <stdlib.h>
struct Node {
int data; // The data contained in this node
struct Node* prev; // A pointer to the previous node in the list
struct Node* next; // A pointer to the next node in the list
};
void display_traversal_forward(struct Node* node)
{
printf("Linked List: ");
// as linked list will end when Node is Null
while( node != NULL ){
printf("%d ",node -> data);
node = node -> next;
}
printf("\n");
}
void display_traversal_backward(struct Node* node)
{
printf("Linked List: ");
// as linked list will end when Node is Null
while( node != NULL ){
printf("%d ",node -> data);
node = node -> prev;
}
printf("\n");
}
int main() {
// Creating the Nodes
struct Node* first;
struct Node* second;
struct Node* third;
struct Node* fourth;
first = (struct Node*)malloc(sizeof(struct Node));
second = (struct Node*)malloc(sizeof(struct Node));
third = (struct Node*)malloc(sizeof(struct Node));
fourth = (struct Node*)malloc(sizeof(struct Node));
first -> data = 10;
second -> data = 20;
third -> data = 30;
fourth -> data = 40;
first -> next = second;
second -> next = third;
third -> next = fourth;
fourth -> next = NULL;
first -> prev = NULL;
second -> prev = first;
third -> prev = second;
fourth -> prev = third;
// Traversing the nodes
display_traversal_forward(first);
display_traversal_backward(fourth);
return 0;
}