请用c语言写代码,要求如下:已知一个正整数序列,个数未知,但至少有一个元素,你的任务是建立一个单链表,并使用该链表存储这个正整数序列,然后统计这个序列中元素的最大值与最小值,计算序列全部元素之和。正整数的输入用-1作为结束标志,注意-1不算这个正整数序列中的元素(不要统计-1)。
时间: 2024-01-22 16:02:44 浏览: 80
```c
#include <stdio.h>
#include <stdlib.h>
struct Node {
int val;
struct Node* next;
};
int main() {
struct Node *head = NULL, *curr = NULL;
int num, max = -1, min = -1, sum = 0;
while (1) {
printf("Enter a positive integer (-1 to end): ");
scanf("%d", &num);
if (num == -1) {
break;
}
if (num < 0) {
printf("Invalid input. Please enter a positive integer.\n");
continue;
}
if (curr == NULL) {
head = (struct Node*) malloc(sizeof(struct Node));
curr = head;
} else {
curr->next = (struct Node*) malloc(sizeof(struct Node));
curr = curr->next;
}
curr->val = num;
curr->next = NULL;
if (max == -1 || num > max) {
max = num;
}
if (min == -1 || num < min) {
min = num;
}
sum += num;
}
if (head == NULL) {
printf("Error: empty sequence.\n");
return 1;
}
printf("Max: %d\n", max);
printf("Min: %d\n", min);
printf("Sum: %d\n", sum);
return 0;
}
```
阅读全文