在C语言中,链表添加节点的方法是通过以下步骤进行的:
struct Node {
int data;
struct Node* next;
};
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->data = 10;
newNode->next = head;
head = newNode;
完整的示例代码如下所示:
#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;
}
此代码将创建一个包含值为10、20和30的节点的链表,并打印出链表的内容:30 20 10。