0

By this code I can't delete the first element of my linked list. Can anybody tell me how to fix it

// defining the linked list (basics)
 #include <stdio.h>
#include <stdlib.h>

struct node
{
int data;
struct node* next;
};

void create(struct node **head, int data)
{
struct node **temp = head;
while (*temp != NULL)
{
    temp = &(*temp) -> next;
}
(*temp) = (struct node*)malloc(sizeof(struct node));
(*temp) -> data = data;
(*temp) -> next = NULL;
}

void del(struct node *head, int data)
{
if (head -> data == data)
{
    struct node *temp = head -> next;
    free(head);
    head = temp;
}
else
{
    while ((head -> next -> data) != data)
    {
        head = head -> next;
    }
    struct node *prev = head;
    free(head -> next);
    struct node *next = head -> next -> next;
    prev -> next = next;
}
}

void prnt(struct node *head)
{
while(head != NULL)
{
    printf("%d",head -> data);
    head = head -> next;
}
}

int main()
{
struct node *begin = NULL;
for (int i = 0; i < 10; i++)
{
    create(&begin, i);
}
prnt(begin);
printf("\n");
del(begin,5);
prnt(begin);
printf("\n");
return 0;
}
1

Deleting a node from a linked list requires changing the pointer to this node. So it might be useful to have a pointer to the head pointer, like

void del(struct node **head_ptr, int data)
{

    while (*head_ptr != NULL && (*head_ptr) -> data != data)
    {
        head_ptr = &((*head_ptr) -> next);
    }
    if (*head_ptr != NULL)
    {
        struct node *next = (*head_ptr) -> next;
        free(*head_ptr);
        *head_ptr = next;
    }
}

and later

    del(&begin, 5);
3
  • What's the mistake in my code? – Rahul Oct 28 '17 at 14:35
  • Also tell me how to write the code by your logic but with this initialization of the function void del(struct node *head_ptr, int data) – Rahul Oct 28 '17 at 14:41
  • Read the first sentence of my answer. You need to change the pointer pointing to the node to be deleted. If it is the head node, and you pass a copy of the head pointer, it's simply impossible. – Blauelf Oct 28 '17 at 16:06

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .