用c语言写一个单链表插入数据的程序
时间: 2023-05-20 18:05:38 浏览: 84
以下是一个用 C 语言实现单链表插入数据的程序:
```c
#include <stdio.h>
#include <stdlib.h>
struct Node {
int data;
struct Node* next;
};
void insert(struct Node** head_ref, int new_data) {
struct Node* new_node = (struct Node*)malloc(sizeof(struct Node));
new_node->data = new_data;
new_node->next = (*head_ref);
(*head_ref) = new_node;
}
void printList(struct Node* node) {
while (node != NULL) {
printf("%d ", node->data);
node = node->next;
}
}
int main() {
struct Node* head = NULL;
insert(&head, 1);
insert(&head, 2);
insert(&head, 3);
insert(&head, 4);
printf("Linked list: ");
printList(head);
return 0;
}
```
这个程序创建了一个 `Node` 结构体,其中包含一个整数 `data` 和一个指向下一个节点的指针 `next`。`insert` 函数用于在链表的头部插入新的节点,`printList` 函数用于打印链表中的所有节点。在 `main` 函数中,我们创建了一个空链表,并向其中插入了四个节点,然后打印了整个链表。