I am newbie in C and I am trying to write a linked list in which each node simply contains an int. The definition of the structure is ok, but I also want to write methods to update this linked list (add element at the tail and delete the head element). (I want to be able to read the most recently added element)
I wrote the functions below, but I don't know where the free should take place and how to implement it. Could anyone help me with this?
typedef struct Node{
Node next = NULL;
int number;
} Node;
void add_node(Node *LL,int val){
// add node to the end of the linked list
new_node = (struct Node *)malloc(1*sizeof(struct Node));
new_node->number = val;
Node n = *LL;
while (n.next != NULL){
n = n.next;
}
n.next = new_node;
}
void delete_head(Node *LL){
// update the head
*LL = LL->next;
//free?
}
void update_LL(*LL,int val){
add_node(*LL,val);
delete_head(*LL);
}
Node next = NULL;-->struct Node *next;in C.delete_head: it is passed a pointer to the head node, but has no idea where that value is stored, and thus cannot update it. You can (as many have explained) delete that node, but whatever is keeping track of the head needs to be updated to the new head.