structnode { int data; structnode *next;// Must have a pointer here };
head
1 2 3 4 5 6 7 8
intmain(){ structnode *head = NULL; structnode *first = malloc(sizeof(structnode)); first -> data = 10; first -> next = NULL;
head = first; // a pointer equals to a pointer }
Append function
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
struct node* Append(struct node * head, int data){ // append a node in the linked list // create the new node structnode *new_node = malloc(sizeof(structnode)); new_node -> data = data; new_node -> next = NULL;
if (head == NULL) return new_node; else { struct node *current = head; while (current -> next != NULL) { current = current -> next; } current -> next = new_node; } return head; }
Print function
1 2 3 4 5 6 7
voidprint_list(struct node *head){ // The head pointer in main will not be modified while (head != null) { printf("%d ", head -> data); head = head -> next; } printf("\n"); }
delete first function
1 2 3 4 5 6 7 8 9 10 11 12
// to delete the very first element, we need a pointer as parameter to change the // one that in main function (the function that calls delete_first function), // otherwise, the 'head' in the upper level function would not be changed voiddelete_first(struct node **phead){ *phead = (*phead) -> next; // *phead equals to the content of the head, equals // to the address of the first element. }
// whenever calling the method in main function, remember that we need to provide // a pointer to a pointer, so as head is a pointer to the first element, which is // struct node *head = NULL; delete_first(&head);
The deleted element is still in the heap: Memory Leak. We need to free that memory.
1 2 3 4 5
voiddelete_first(struct node **phead){ structnode *deleted = *phead;// store the address of the deleted element *phead = (*phead) -> next; free(deleted); }