diff --git a/doublylinkedlist.c b/doublylinkedlist.c new file mode 100644 index 00000000..d4d4b789 --- /dev/null +++ b/doublylinkedlist.c @@ -0,0 +1,59 @@ +#include +#include + +// Define the structure for a doubly linked list node +struct Node { + int data; + struct Node* prev; + struct Node* next; +}; + +// Function to create a new node +struct Node* createNode(int data) { + struct Node* newNode = (struct Node*)malloc(sizeof(struct Node)); + if (newNode == NULL) { + printf("Memory allocation failed!\n"); + exit(1); + } + newNode->data = data; + newNode->prev = NULL; + newNode->next = NULL; + return newNode; +} + +// Function to insert a node at the beginning of the list +void insertAtBeginning(struct Node** head, int data) { + struct Node* newNode = createNode(data); + if (*head == NULL) { + *head = newNode; + } else { + newNode->next = *head; + (*head)->prev = newNode; + *head = newNode; + } +} + +// Function to display the doubly linked list +void displayList(struct Node* head) { + struct Node* current = head; + while (current != NULL) { + printf("%d <-> ", current->data); + current = current->next; + } + printf("NULL\n"); +} + +int main() { + struct Node* head = NULL; + + // Insert some elements at the beginning of the list + insertAtBeginning(&head, 3); + insertAtBeginning(&head, 5); + insertAtBeginning(&head, 7); + + // Display the list + printf("Doubly Linked List: "); + displayList(head); + + return 0; +} diff --git a/doublyll.c b/doublyll.c new file mode 100644 index 00000000..d4d4b789 --- /dev/null +++ b/doublyll.c @@ -0,0 +1,59 @@ +#include +#include + +// Define the structure for a doubly linked list node +struct Node { + int data; + struct Node* prev; + struct Node* next; +}; + +// Function to create a new node +struct Node* createNode(int data) { + struct Node* newNode = (struct Node*)malloc(sizeof(struct Node)); + if (newNode == NULL) { + printf("Memory allocation failed!\n"); + exit(1); + } + newNode->data = data; + newNode->prev = NULL; + newNode->next = NULL; + return newNode; +} + +// Function to insert a node at the beginning of the list +void insertAtBeginning(struct Node** head, int data) { + struct Node* newNode = createNode(data); + if (*head == NULL) { + *head = newNode; + } else { + newNode->next = *head; + (*head)->prev = newNode; + *head = newNode; + } +} + +// Function to display the doubly linked list +void displayList(struct Node* head) { + struct Node* current = head; + while (current != NULL) { + printf("%d <-> ", current->data); + current = current->next; + } + printf("NULL\n"); +} + +int main() { + struct Node* head = NULL; + + // Insert some elements at the beginning of the list + insertAtBeginning(&head, 3); + insertAtBeginning(&head, 5); + insertAtBeginning(&head, 7); + + // Display the list + printf("Doubly Linked List: "); + displayList(head); + + return 0; +}