简体   繁体   中英

can't remove first node from linked list

today i had C exam, and i could't manage to remove first node from the linked list. In my case, it delets the first element, but head is still pointing to a first node '0'. I am sitting right now and googling for a solution, but can't find anything. The fuction head ( struct t_node *delete_first(struct t_node *head) )was already given by the Professor.

 #include <stdio.h>
    #include <stdlib.h>

struct t_node {
     int number;
     struct t_node *next;
};

struct t_node * insert (struct t_node *head, int num){
  struct t_node * new_node = malloc(sizeof(struct t_node));
  new_node->number = num;
  new_node->next = head;

  return new_node;
}

void printlistvalues(struct t_node *head){
  while (head != NULL){
    printf("%d\n", head->number);
    head = head->next;
  }
}
struct t_node *delete_first(struct t_node *head){
struct t_node *help = head;

head = head->next;
free(help);


return head;
}

int main(){
 struct t_node *list = NULL;

 list = insert(list, 10);
 list = insert(list, 20);
 list = insert(list, 30);
 list = insert(list, 40);
 list = insert(list, 50);

 printlistvalues(list);
 printf("\n");
 delete_first(list);
 printlistvalues(list);

 return 0;
}

You have to write

list = delete_first(list);

Also the function itself should look like

struct t_node * delete_first( struct t_node *head )
{
    if ( head != NULL )
    {
        struct t_node *tmp = head;
        head = head->next;
        free( tmp );
    }

    return head;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM