0

For my program, I need to create a function that accepts a linkedlist as a parameter, then deletes the first node from the list. There are other steps, but I'd like to get this sub-part done first.

This is what I have so far:

 struct node *del_the_first(struct node *head)  {

 struct node *temp = head;
 head = head->next;
 temp->next = NULL;
 return NULL;

 }

I believe my solution is correct, however I have no way of testing it at this time. I'm more interested in why I am or am not wrong.

Mr. Roshan
  • 1,777
  • 13
  • 33
oAUTHo123
  • 29
  • 2
  • To be able to modify pointer your function must accept pointer to pointer as argument. In most cases it makes sense to make head global. – purec May 26 '18 at 08:25

2 Answers2

0

What you should test is:

  • print the value of temp at the end of the function,
    this is what head was at the start of the function
  • print the value of head at the end of the function,
    which is what the head of the list should be after returning for the function
  • print (from outside the function, e.g. from main) the value of the variable
    which is supposed to point to the head of the list,
    especially after deleting the first element

You will notice that outside your function the pointer to the head of the list is still pointing to where the first element still is.
You do not want that, do you? The variable which points to the head of the list is supposed to point to the second element of the list, isn't it?

If above is true, you probably want to use free() on the formerly first element of the list, before returning from the function.

Read this for more information on how to fix the first problem:
Parameter Passing in C - Pointers, Addresses, Aliases

Basically, you will want to return the new value of the pointer to the head of the list:

struct node *del_the_first(struct node *head)
{
    struct node *temp = head;
    head = head->next;
    temp->next = NULL; /* not really needed */
    free(temp);
    return head;
}

Then call it like:

global_head = del_the_first(global_head);

Note that this code assumes that the list is not empty,
see the answer by ccpan on how to remove this assumption.

Yunnosch
  • 26,130
  • 9
  • 42
  • 54
0

You need to check for boundary conditions. Suppose your linkedList is empty, then during runtime, you will get a segmentation fault. So you need to check if head pointer is NULL or not before trying to access next node.

Also, I don't know why you are returning a NULL. You are most probably wanting to return the new head node pointer.

struct node *del_the_first(struct node *head)  {

    if (head != NULL) {
        struct node *temp = head;
        head = head->next;
        free(temp);
        temp = NULL;
    }

    return head;
}

slimmsady
  • 56
  • 1
  • 3