用C语言写一个用二级指针实现的单链表
时间: 2023-05-17 09:07:28 浏览: 66
以下是用C语言写一个用二级指针实现的单链表的代码:
```c
#include <stdio.h>
#include <stdlib.h>
typedef struct node {
int data;
struct node *next;
} Node;
void insert(Node **head, int data) {
Node *new_node = (Node *) malloc(sizeof(Node));
new_node->data = data;
new_node->next = *head;
*head = new_node;
}
void print_list(Node *head) {
while (head != NULL) {
printf("%d ", head->data);
head = head->next;
}
printf("\n");
}
int main() {
Node *head = NULL;
insert(&head, 1);
insert(&head, 2);
insert(&head, 3);
print_list(head);
return 0;
}
```
这个程序使用了二级指针来实现单链表。在 `insert` 函数中,我们首先创建一个新的节点,然后将它的 `next` 指针指向当前链表的头节点,最后将链表的头指针指向新节点。在 `print_list` 函数中,我们遍历整个链表并打印每个节点的数据。在 `main` 函数中,我们创建一个空链表,然后插入三个节点并打印整个链表。