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:
- 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;
};
- Create a new node and allocate memory for it. For example:
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
- Assigning a new value to a new node. For example:
newNode->data = 10;
- Point the next pointer of the new node to the head node of the linked list. For example:
newNode->next = head;
- 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.