c语言用二级指针实现对链表输出
时间: 2024-05-03 18:21:31 浏览: 19
下面是一个用二级指针实现对链表输出的示例代码:
```c
#include <stdio.h>
#include <stdlib.h>
typedef struct node {
int data;
struct node *next;
} Node;
void printList(Node **head) {
Node *current = *head;
while (current != NULL) {
printf("%d ", current->data);
current = current->next;
}
printf("\n");
}
void insert(Node **head, int data) {
Node *newNode = (Node *)malloc(sizeof(Node));
newNode->data = data;
newNode->next = NULL;
if (*head == NULL) {
*head = newNode;
} else {
Node *current = *head;
while (current->next != NULL) {
current = current->next;
}
current->next = newNode;
}
}
int main() {
Node *head = NULL;
insert(&head, 1);
insert(&head, 2);
insert(&head, 3);
insert(&head, 4);
insert(&head, 5);
printList(&head);
return 0;
}
```
在上面的代码中,我们定义了一个 `Node` 结构体来表示链表中的节点,其中包含一个整数数据和指向下一个节点的指针。然后我们定义了一个 `printList` 函数,它接受一个二级指针 `head`,并通过循环遍历链表中的所有节点,输出它们的数据。我们还定义了一个 `insert` 函数,它接受一个二级指针 `head` 和一个整数数据,用于向链表中插入一个新节点。最后,我们在 `main` 函数中创建了一个空链表,并通过调用 `insert` 函数向其中插入了一些节点,然后调用 `printList` 函数输出整个链表的数据。