Monday, 9 December 2024

Write a Program linked list create ,insert,first .

#include <stdio.h>

#include <stdlib.h>


// Define the structure of a node

struct Node {

    int data;

    struct Node* next;

};


// Function to create a new node

struct Node* createNode(int data) {

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

    newNode->data = data;

    newNode->next = NULL;

    return newNode;

}


// Function to insert a node at the beginning

struct Node* insertAtFirst(struct Node* head, int data) {

    struct Node* newNode = createNode(data);

    newNode->next = head;

    return newNode;

}


// Function to display the linked list

void displayList(struct Node* head) {

    struct Node* temp = head;

    while (temp != NULL) {

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

        temp = temp->next;

    }

    printf("NULL\n");

}


int main() {

    struct Node* head = NULL; // Initially, the list is empty


    // Create and insert elements

    head = insertAtFirst(head, 10);

    head = insertAtFirst(head, 20);

    head = insertAtFirst(head, 30);


    // Display the list

    printf("Linked List: ");

    displayList(head);


    return 0;

}