Insert at beginning in Linked list

 #include <stdio.h>

#include <stdlib.h>


struct Node {

    int data;

    struct Node* next;

};


void insertAtBeginning(struct Node** head, int value) {

    struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));

    newNode->data = value;

    newNode->next = *head;

    *head = newNode;

}


void printList(struct Node* head) {

    while (head != NULL) {

        printf("%d -> ", head->data);

        head = head->next;

    }

    printf("NULL\n");

}


int main() {

    struct Node* head = NULL;


    insertAtBeginning(&head, 10);

    insertAtBeginning(&head, 20);

    insertAtBeginning(&head, 30);


    printList(head);


    return 0;

}

KRISHNA

Author & Editor

Thanks for visiting xmonocodes , i hope you are getting everything you want.

0 comments:

Post a Comment