c语言链表查找最大值
时间: 2023-12-30 20:23:27 浏览: 65
以下是使用C语言链表查找最大值的示例代码:
```c
#include <stdio.h>
#include <stdlib.h>
// 定义链表节点结构
struct Node {
int data;
struct Node* next;
};
// 在链表末尾插入节点
void insert(struct Node** head, int value) {
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node)); newNode->data = value;
newNode->next = NULL;
if (*head == NULL) {
*head = newNode;
} else {
struct Node* current = *head;
while (current->next != NULL) {
current = current->next;
}
current->next = newNode;
}
}
// 查找链表中的最大值
int findMax(struct Node* head) {
if (head == NULL) {
printf("链表为空\n");
return -1;
}
int max = head->data;
struct Node* current = head->next;
while (current != NULL) {
if (current->data > max) {
max = current->data;
}
current = current->next;
}
return max;
}
int main() {
struct Node* head = NULL;
// 插入节点
insert(&head, 100);
insert(&head, 2);
insert(&head, 3);
insert(&head, -2);
insert(&head, -8);
insert(&head, -6);
insert(&head, -9);
insert(&head, -10);
insert(&head, 50);
insert(&head, 2);
insert(&head, -1);
// 查找最大值
int max = findMax(head);
printf("链表中的最大值为:%d\n", max);
return 0;
}
```