写一段链表的遍历c++代码
时间: 2023-05-23 10:06:24 浏览: 51
以下是链表遍历的C代码:
```c
#include <stdio.h>
#include <stdlib.h>
// 定义链表结构体
struct Node
{
int data;
struct Node* next;
};
// 遍历链表并打印数据
void traverseLinkedList(struct Node* head)
{
while (head != NULL) // 循环遍历链表直到尾部
{
printf("%d ", head->data); // 打印当前节点的数据
head = head->next; // 指向下一个节点
}
}
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;
second->data = 2;
third->data = 3;
// 连接节点
head->next = second;
second->next = third;
third->next = NULL;
// 遍历链表并打印数据
traverseLinkedList(head);
return 0;
}
```
该代码定义了链表结构体,实现了遍历链表并打印数据的函数。在主函数中创建了三个节点,并根据需要连接它们以形成链表。最后调用遍历函数以输出每个节点的数据。