C Program for Deletion from beginning in doubly linked list
Deletion from starting node in doubly linked list
In this article we will learn C Program for Deletion from beginning in doubly linked list, the task is to delete the first node of the doubly linked list and assign head to the second node.In the doubly linked list we can traverse in both direction because it has two pointer next and previous to move in both directions.
For Example :-
Input : 61 4 77 10 32
Output : 4 77 10 32
Deletion From Beginning in Doubly Linked List
Implementation needed for deleting node in the doubly linked list
- Firstly we have to delete the head node (start or first node) and copy the head node in a extra node.
- And the task is make the second node as the head node.
- Lastly we have to do is delete(free) the extra node.
How to made node Structure in the doubly linked list
struct node { struct node *prev; int data; struct node *next; }
Algorithm require for deleting node from the beginning in the linked list
- NOW IF HEAD = NULL (GO TO STEP 6)
- ASSIGN POINTER = HEAD
- ASSIGN HEAD = HEAD → NEXT
- ASSIGN HEAD → PREVIOUS = NULL
- THAN FREE OR DELETE POINTER
- EXIT OR RETURN
C Program for Deletion From Beginning in a Doubly Linked List
Run
#include<stdio.h> #include<stdlib.h> 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 deleteFront (struct Node **head) { struct Node *tempNode = *head; // if DLL is empty if (*head == NULL) { printf ("Linked List Empty, nothing to delete\n"); return; } // if Linked List has only 1 node if (tempNode->next == NULL) { printf ("%d deleted\n\n", tempNode->data); *head = NULL; return; } // move head to next node *head = (*head)->next; // assign head node's previous to NULL (*head)->prev = 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; printf ("List in Forward direction: "); 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 ("List Before Deletion: "); display (head); deleteFront (&head); printf ("List After Deletion: "); display (head); return 0; }
Output
List Before Deletion: List in Forward direction: 12 11 10 9 8 7 12 deleted List After Deletion: List in Forward direction: 11 10 9 8 7
Login/Signup to comment