C语言通过遍历链表分行输出链表内容
时间: 2024-01-04 19:19:30 浏览: 78
C语言通过遍历链表分行输出链表内容的方法如下:
```c
#include <stdio.h>
// 定义链表节点结构体
struct Node {
int data;
struct Node* next;
};
// 遍历链表分行输出链表内容的函数
void printLinkedList(struct Node* head) {
struct Node* current = head;
while (current != NULL) {
printf("%d ", current->data);
current = current->next;
if (current != NULL) {
printf("\n");
}
}
}
int main() {
// 创建链表
struct Node* head = NULL;
struct Node* second = NULL;
struct Node* third = NULL;
head = (struct Node*)malloc(sizeof(struct Node));
second = (struct Node*)malloc(sizeof(struct Node));
third = (struct Node*)malloc(sizeof(struct Node));
head->data = 1;
head->next = second;
second->data = 2;
second->next = third;
third->data = 3;
third->next = NULL;
// 调用函数输出链表内容
printLinkedList(head);
return 0;
}
```
运行以上代码,将会输出链表的内容,每个节点的数据占一行。
阅读全文