From 5fa5fdceeebef5178cc4fb797aa330e9a597c1e3 Mon Sep 17 00:00:00 2001 From: Abhishek Choudhary <135415468+iamabhishek2828@users.noreply.github.com> Date: Sat, 28 Oct 2023 13:17:06 +0530 Subject: [PATCH] Create Doublydeletion.c This code will perform deletion operation at the end of doubly linked list --- C/Doublydeletion.c | 95 ++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 95 insertions(+) create mode 100644 C/Doublydeletion.c diff --git a/C/Doublydeletion.c b/C/Doublydeletion.c new file mode 100644 index 0000000..a9b1fa1 --- /dev/null +++ b/C/Doublydeletion.c @@ -0,0 +1,95 @@ +#include +#include + +struct Node +{ + int data; + struct Node *next; + struct Node *prev; +}; + +void insert (struct Node **head, int data) +{ + + struct Node *freshNode = (struct Node *) malloc (sizeof (struct Node)); + + freshNode->data = data; + freshNode->next = *head; + freshNode->prev = NULL; + + // If the linked list already had atleast 1 node + if (*head != NULL) + (*head)->prev = freshNode; + + // freshNode will become head + *head = freshNode; +} + +void deleteEnd (struct Node **head) +{ + struct Node *tempNode = *head; + + // if DLL is empty + if (*head == NULL) + { + printf ("Linked List Empty, nothing to delete\n\n"); + return; + } + + // if Linked List has only 1 node + if (tempNode->next == NULL) + { + printf ("%d deleted\n\n", tempNode->data); + *head = NULL; + return; + } + + // else traverse to the last node + while (tempNode->next != NULL) + tempNode = tempNode->next; + + struct Node *secondLast = tempNode->prev; + + // Curr assign 2nd last node's next to Null + secondLast->next = NULL; + + printf ("%d deleted\n\n", tempNode->data); + free (tempNode); +} + +//function to print the doubly linked list +void display (struct Node *node) +{ + struct Node *end = NULL; + + + while (node != NULL) + { + printf (" %d ", node->data); + end = node; + node = node->next; + } + + printf ("\n\n"); +} + +int main () +{ + struct Node *head = NULL; + + insert (&head, 7); + insert (&head, 8); + insert (&head, 9); + insert (&head, 10); + insert (&head, 11); + insert (&head, 12); + + printf("Linked List Before Deletion"); + display (head); + + deleteEnd (&head); + printf("Linked List After Deletion"); + display (head); + + return 0; +}