Given only a pointer to a node to be deleted in a singly linked list, how do you delete it?
Code:#include <stdio.h> #include <stdlib.h> struct linkedList{ int element; struct linkedList* next; }; typedef struct linkedList* List; void deleteNode(List Node) { List tmp; if(Node){ // If current node is not NULL tmp = List->next; // take backup of next Node Node->element = Node->next->element; // replace current node element with next Node element Node->next = Node->next->next; // change next pointer to next to next free(tmp); // free the next Node which was taken backup } return; }
This code doesn't handle the boundary cases like what if Node to be deleted is the last node i.e. Node->next=NULL , so in above code this condition should be handled as well.
There are currently 1 users browsing this thread. (0 members and 1 guests)
Bookmarks