编写一个链表求出最大值的代码使用c语言编写
时间: 2023-06-02 22:05:50 浏览: 42
好的,以下是用C语言编写求链表最大值的代码:
```
#include <stdio.h>
#include <stdlib.h>
struct Node {
int value;
struct Node *next;
};
int main() {
// 创建链表
struct Node *head = (struct Node*)malloc(sizeof(struct Node));
head->value = 0; // 头节点的值为0
head->next = NULL; // 头节点的next为NULL
// 向链表中添加节点
struct Node *p = head;
for (int i=1; i<=5; i++) {
struct Node *temp = (struct Node*)malloc(sizeof(struct Node));
temp->value = i;
temp->next = NULL;
p->next = temp;
p = temp;
}
// 遍历链表,求最大值
int max_val = head->next->value;
p = head->next->next;
while (p != NULL) {
if (p->value > max_val) {
max_val = p->value;
}
p = p->next;
}
// 输出结果
printf("最大值为:%d\n", max_val);
return 0;
}
```