I made the following functions for deleting a node of a singly linked list.
1. Can these functions be improved furthur?
2. Is it necessary to free the memory of the node that is deleted?
nodep deleteByValue(nodep p, int value) {
nodep temp = p;
if(temp->data == value) return temp->next;
while(temp->next) {
if(temp->next->data == value) {
temp->next = temp->next->next;
return p;
}
temp = temp->next;
}
printf("\nError: Node not found!\n");
return p;
}
nodep deleteByPosition(nodep p, int pos) {
nodep temp = p;
int i = 1;
if(pos > countNodes(p)) {
printf("Error: Input position > Total nodes.\n");
return p;
}
if(pos == 1) return p->next;
while(i < pos-1) {
temp = temp->next;
i++;
}
temp->next = temp->next->next;
return p;
}
I have defined the linked list as
typedef struct listNode * nodep;
typedef struct listNode {
int data;
nodep next;
}node;