Cover Image for Add Node to Linked List in C
111 views

Add Node to Linked List in C

To add a node to a singly linked list in C, you need to perform a few steps:

  1. Create a new node.
  2. Set the data of the new node.
  3. Update the pointers to insert the new node into the list.

Here’s a sample C program to add a node to the end of a singly linked list:

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

// Define a structure for a node in the linked list
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));
    if (newNode == NULL) {
        printf("Memory allocation failed.\n");
        exit(1);
    }
    newNode->data = data;
    newNode->next = NULL;
    return newNode;
}

// Function to add a node to the end of the linked list
void appendNode(struct Node** head, int data) {
    struct Node* newNode = createNode(data);

    // If the linked list is empty, make the new node the head
    if (*head == NULL) {
        *head = newNode;
        return;
    }

    // Traverse to the end of the linked list
    struct Node* current = *head;
    while (current->next != NULL) {
        current = current->next;
    }

    // Append the new node to the end
    current->next = newNode;
}

// Function to display the linked list
void displayList(struct Node* head) {
    struct Node* current = head;
    while (current != NULL) {
        printf("%d -> ", current->data);
        current = current->next;
    }
    printf("NULL\n");
}

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

    // Add nodes to the linked list
    appendNode(&head, 10);
    appendNode(&head, 20);
    appendNode(&head, 30);

    // Display the linked list
    printf("Linked List: ");
    displayList(head);

    return 0;
}

In this program:

  • We define a struct Node to represent a node in the linked list. It contains an integer data field and a pointer to the next node.
  • The createNode function is used to create a new node and initialize its data and next pointer.
  • The appendNode function adds a new node to the end of the linked list. If the list is empty, the new node becomes the head of the list. Otherwise, it traverses the list to find the last node and appends the new node to it.
  • The displayList function is used to print the elements of the linked list.

In the main function, we create an empty linked list, add nodes to it using appendNode, and then display the linked list using displayList.

YOU MAY ALSO LIKE...

The Tech Thunder

The Tech Thunder

The Tech Thunder


COMMENTS