logo

Adding elements to a linked list

#include <stdio.h> #include <stdlib.h> #include <string.h> typedef struct Node { int x; struct Node* next; } Node; void insert_end(Node** root, int value) { Node* new_node = malloc(sizeof(Node)); if (new_node == NULL) { exit(1); } new_node->next = NULL; new_node->x = value; if (*root == NULL) { *root = new_node; return; } Node* curr = *root; while (curr->next != NULL) { curr = curr->next; } curr->next = new_node; } int main(int argc, char* argv[]) { Node* root = NULL; insert_end(&root, -2); insert_end(&root, 11); insert_end(&root, 22); for (Node* curr = root; curr != NULL; curr = curr->next) { printf("%d\n", curr->x); } // List is not freed! return 0; }
Course thumb

The C programming language made simple