从链表头查询到链表尾,用c写出代码
时间: 2024-03-13 14:21:42 浏览: 22
以下是用C语言编写的从链表头查询到链表尾的代码示例:
```c
#include <stdio.h>
#include <stdlib.h>
// 定义链表节点结构体
struct Node {
int data;
struct Node* next;
};
// 数据初始化函数
void initList(struct Node** head, int num) {
struct Node* cur = *head;
for (int i = 1; i <= num; i++) {
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
if (!newNode) exit(1);
newNode->data = i;
newNode->next = NULL;
if (!cur) {
*head = newNode;
cur = newNode;
}
else {
cur->next = newNode;
cur = newNode;
}
}
}
// 从头到尾输出
void printList(struct Node* head) {
struct Node* cur = head;
while (cur) {
printf("%d ", cur->data);
cur = cur->next;
}
}
int main() {
struct Node* head = NULL;
initList(&head, 10);
printf("链表输出:");
printList(head);
return 0;
}
```
运行结果为:
```
链表输出:1 2 3 4 5 6 7 8 9 10
```
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)