Implement the following functions for linked lists. You can assume that all the
ID: 3819248 • Letter: I
Question
Implement the following functions for linked lists. You can assume that all the nodes in the linked list are distinct and each node appears in the list at most once. node *delete(node *head, int k) node *recursivedelete (node *head, int k) delete deletes the node with info k from the linked list and returns the new linked list. It returns the linked list without modification if k does not appear in the list. recursivedelete is a recursive function that deletes the node with info k from the linked list and returns the new linked list. It returns the linked list without modification if k does not appear in the list.Explanation / Answer
void delete(struct node *head,int x)
{
int k=1;
struct node *p,*q;
if(head==NULL)
printf("List is empty ");
p=head;
if(p->data ==x)
{
head=head->next;
free(p);
//printf("head dleted ");
}
else
{
while(p!=NULL && p->data!=x)
{
q=p;
p=p->next;
}
if(p==NULL)
printf("element not exist ");
else
{
q->next=p->next;
free(p);
// printf("node deleted ");
}
}
}
Recursive solution is:
void recursivedelete(struct node *head, int data)
{
struct node *current=head;
if (current == NULL)
{
return;
}
//node to be deleted is the first one
if (current->data == data)
{
struct node *t=current;
current=current->next;
free(t);
return;
}
if (current->next && current->next->data == data) // next exists and must be deleted
{
struct node *temp = current->next; // Step 1: save ptr to next
current->next = temp->next; // Step 2: reassign current->next ptr
free(temp); // Step 3: delete the node
return;
}
return recursivedelete(current->next, data);
}