What is the method for adding nodes to a linked list in the C language?

In C language, the method of adding a node to a linked list is done through the following steps:

  1. Create a structure to represent a node, which includes a data member and a pointer member that points to the next node. For example:
struct Node {
    int data;
    struct Node* next;
};
  1. Create a new node and allocate memory for it. For example:
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
  1. Assigning a new value to a new node. For example:
newNode->data = 10;
  1. Point the next pointer of the new node to the head node of the linked list. For example:
newNode->next = head;
  1. Set the new node as the new head node of the linked list. For example:
head = newNode;

The complete example code is provided below:

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

struct Node {
    int data;
    struct Node* next;
};

void insert(struct Node** head, int data) {
    struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
    newNode->data = data;
    newNode->next = *head;
    *head = newNode;
}

void printList(struct Node* head) {
    struct Node* temp = head;
    while (temp != NULL) {
        printf("%d ", temp->data);
        temp = temp->next;
    }
    printf("\n");
}

int main() {
    struct Node* head = NULL;

    insert(&head, 10);
    insert(&head, 20);
    insert(&head, 30);

    printList(head);

    return 0;
}

This code will create a linked list with nodes containing the values 10, 20, and 30, and print out the contents of the list: 30 20 10.

Leave a Reply 0

Your email address will not be published. Required fields are marked *


广告
Closing in 10 seconds
bannerAds