请写代码:已知一个正整数序列,个数未知,但至少有一个元素,你的任务是建立一个单链表,并使用该链表存储这个正整数序列,然后统计这个序列中元素的最大值与最小值,计算序列全部元素之和。正整数的输入用-1作为结束标志,注意-1不算这个正整数序列中的元素(不要统计-1)。
时间: 2024-02-05 10:13:21 浏览: 182
以下是使用 Python 语言实现的代码:
```python
class Node:
def __init__(self, data=None):
self.data = data
self.next = None
# 建立单链表
head = Node()
tail = head
while True:
num = int(input("请输入一个正整数:"))
if num == -1:
break
node = Node(num)
tail.next = node
tail = node
# 统计最大值、最小值和元素之和
curr = head.next
max_num, min_num, total = curr.data, curr.data, 0
while curr:
if curr.data > max_num:
max_num = curr.data
if curr.data < min_num:
min_num = curr.data
total += curr.data
curr = curr.next
# 输出结果
print("最大值为:", max_num)
print("最小值为:", min_num)
print("元素之和为:", total)
```
相关问题
请用c语言写代码,要求如下:已知一个正整数序列,个数未知,但至少有一个元素,你的任务是建立一个单链表,并使用该链表存储这个正整数序列,然后统计这个序列中元素的最大值与最小值,计算序列全部元素之和。正整数的输入用-1作为结束标志,注意-1不算这个正整数序列中的元素(不要统计-1)。
```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;
}
```
用C语言帮我完成一下程序:已知一个正整数序列,个数未知,但至少有一个元素,你的任务是建立一个单链表,并使用该链表存储这个正整数序列,然后统计这个序列中元素的最大值与最小值,计算序列全部元素之和。正整数的输入用-1作为结束标志,注意-1不算这个正整数序列中的元素(不要统计-1)。
好的,下面是用C语言实现的程序:
```c
#include <stdio.h>
#include <stdlib.h>
typedef struct node {
int data;
struct node *next;
} Node;
int main() {
Node *head = NULL;
int num, max, min, sum = 0;
printf("请输入正整数序列(以-1结束):\n");
while (1) {
scanf("%d", &num);
if (num == -1) {
break;
}
Node *new_node = (Node *)malloc(sizeof(Node));
new_node->data = num;
new_node->next = NULL;
if (head == NULL) {
head = new_node;
} else {
Node *p = head;
while (p->next != NULL) {
p = p->next;
}
p->next = new_node;
}
}
if (head == NULL) {
printf("序列为空!\n");
return 0;
}
max = min = sum = head->data;
Node *p = head->next;
while (p != NULL) {
if (p->data > max) {
max = p->data;
}
if (p->data < min) {
min = p->data;
}
sum += p->data;
p = p->next;
}
printf("最大值:%d\n", max);
printf("最小值:%d\n", min);
printf("元素之和:%d\n", sum);
p = head;
while (p != NULL) {
Node *q = p->next;
free(p);
p = q;
}
return 0;
}
```
程序的思路是先读入正整数序列,然后建立一个单链表存储这个序列。接着统计序列中的最大值、最小值和元素之和。最后释放链表中的所有节点。注意要处理输入为空序列的情况。
阅读全文
相关推荐












