在C語言中,鏈表添加節(jié)點的方法是通過以下步驟進行的:
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;
}
此代碼將創(chuàng)建一個包含值為10、20和30的節(jié)點的鏈表,并打印出鏈表的內(nèi)容:30 20 10。