C实现【问题描述】创建一个单链表,并求其最大值。 【输入形式】从键盘输入若干个整数,以空格分开,-1作为输入结束。 【输出形式】如果存在最大值,则输出;否则输出No answer! 【样例输入】65 12 6 78 5 -1 【样例输出】78
时间: 2023-12-03 21:05:16 浏览: 34
以下是C语言的实现代码:
```c
#include <stdio.h>
#include <stdlib.h>
// 定义链表节点结构体
struct Node {
int data;
struct Node *next;
};
// 创建链表函数
struct Node *createList() {
int num;
struct Node *head, *p, *q;
head = (struct Node *)malloc(sizeof(struct Node));
head->next = NULL;
q = head;
scanf("%d", &num);
while(num != -1) {
p = (struct Node *)malloc(sizeof(struct Node));
p->data = num;
p->next = NULL;
q->next = p;
q = p;
scanf("%d", &num);
}
return head;
}
// 求最大值函数
int max(struct Node *head) {
if (head->next == NULL) {
return -1; // 链表为空,返回-1
}
int maxNum = head->next->data; // 初始化最大值为链表的第一个值
struct Node *p = head->next->next;
while(p != NULL) {
if (p->data > maxNum) {
maxNum = p->data;
}
p = p->next;
}
return maxNum;
}
int main() {
struct Node *list = createList();
int maxNum = max(list);
if (maxNum == -1) {
printf("No answer!\n");
} else {
printf("%d\n", maxNum);
}
return 0;
}
```
输入样例:
```
65 12 6 78 5 -1
```
输出样例:
```
78
```