how to push node using linked list c

To push a node to a linked list in C, you can follow these steps:

  1. Create a new node: Allocate memory for a new node using the malloc() function and assign the data value to the node.
  2. Set the next pointer: Set the next pointer of the new node to point to the current head of the linked list.
  3. Update the head pointer: Set the head pointer of the linked list to point to the new node, making it the new head of the list.

Here's an example implementation:

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

// Define the structure for a node
struct Node {
    int data;
    struct Node* next;
};

// Function to push a node to the linked list
void push(struct Node head, int newData) {
    // Create a new node
    struct Node newNode = (struct Node)malloc(sizeof(struct Node));

    // Assign the data value to the new node
    newNode->data = newData;

    // Set the next pointer of the new node to point to the current head
    newNode->next = *head;

    // Update the head pointer to point to the new node
    *head = newNode;
}

int main() {
    // Create an empty linked list
    struct Node* head = NULL;

    // Push nodes to the linked list
    push(&head, 3);
    push(&head, 2);
    push(&head, 1);

    // Print the linked list
    struct Node* current = head;
    while (current != NULL) {
        printf("%d ", current->data);
        current = current->next;
    }

    return 0;
}

In this example, the push() function takes a double pointer to the head of the linked list and the data value for the new node. It creates a new node, assigns the data value, sets the next pointer to the current head, and updates the head pointer to point to the new node. Finally, the main function demonstrates how to push nodes to the linked list and prints the elements of the linked list.

I hope this helps! Let me know if you have any further questions.