Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,851 questions

51,772 answers

573 users

How to add element at the beginning of a linked list in C

1 Answer

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

typedef struct Node {
    int x;
    struct Node *next;
} Node;
 
void add_first(Node **root, int value) {
    Node* new_node = malloc(sizeof(int));
    if (new_node == NULL) {
        puts("malloc error");
        exit(1);
    }
    
    new_node->x = value;
    new_node->next = *root;
    
    *root = new_node;
} 
 
void add_node(Node **root, int value) {
    Node *new_node = malloc(sizeof(Node));
     
    if (new_node == NULL) {
        puts("malloc error");
        exit(1);
    }
     
    new_node->next = NULL;
    new_node->x = value;
     
    if (*root == NULL) {
        *root = new_node;
        return;
    }
     
    Node* current = *root;
    while (current->next != NULL) {
        current = current->next;
    }
    current->next = new_node;
}
 
void free_LinkedList(Node *root) {
    Node *next;
    while (root != NULL)  {  
        next = root->next;  
        free(root);  
        root = next;  
    }  
}
 
int main() {
    Node *root = NULL;
     
    add_node(&root, 7);
    add_node(&root, 3);
    add_node(&root, 78);
    add_node(&root, 200);
     
    for (Node *current = root; current != NULL; current = current->next) {
        printf("%d\n", current->x);
    }
    
    add_first(&root, 9817);
    
    puts("\n");
    for (Node *current = root; current != NULL; current = current->next) {
        printf("%d\n", current->x);
    }
     
    free_LinkedList(root);
 
    return 0;
}
 
 
 
/*
run:
 
7
3
78
200


9817
7
3
78
200

*/

 



answered Jan 1, 2021 by avibootz

Related questions

...