问题 A 实验11_4_初识链表
题目描述
已知一个正整数序列,个数未知,但至少有一个元素,你的任务是建立一个单链表,并使用该链表存储这个正整数序列,然后统计这个序列中元素的最大值与最小值,计算序列全部元素之和。正整数的输入用-1作为结束标志,注意-1不算这个正整数序列中的元素(不要统计-1)。
输入
一个正整数序列,正整数序列元素的个数未知,但以输入“-1”结束,输入“-1”前至少输入一个正整数。序列中的元素范围在1—999999999之间。
输出
三个正整数,即最大值、最小值、所有元素之和。
数据最多的测试用例节点数在1000这个数量级,所有整数可以用int型存储。
请注意输入输出格式。
样例输入 Copy
1 4 99 21 50 61 32 4 -1
样例输出 Copy
The maximum,minmum and the total are:99 1 272
/* creat the linked list and get the max, min and sum
@author: CangCheng
@date: 13/3/2021
*/
#include<stdio.h>
#include <stdlib.h>
struct node {
int data;
int *nextPtr;
};
struct node *creatLinkedList(struct node *headPtr);
void delLinkedList(struct node *headPtr);
int getMax(struct node *headPtr);
int getMin(struct node *headPtr);
int getSum(struct node *headPtr);
int main() {
struct node *headPtr = NULL;
int max, min, sum;
headPtr = creatLinkedList(headPtr);
max = getMax(headPtr);
min = getMin(headPtr);
sum = getSum(headPtr);
printf("The maximum,minmum and the total are:%d %d %d", max, min, sum);
delLinkedList(headPtr);
return 0;
}
//创建链表
struct node *creatLinkedList(struct node *headPtr) {
struct node *newPtr, *currentPtr;
int num;
scanf("%d", &num);
while (num != -1) {
newPtr = malloc(sizeof(struct node));
newPtr->data = num;
newPtr->nextPtr = NULL;
if (headPtr == NULL) {
currentPtr = newPtr;
headPtr = currentPtr;
} else {
currentPtr->nextPtr = newPtr;
currentPtr = newPtr;
}
scanf("%d", &num);
}
return headPtr;
}
//删除链表
void delLinkedList(struct node *headPtr) {
struct node *thisPtr, *thatPtr;
thisPtr = headPtr;
while (thisPtr != NULL) {
thatPtr = thisPtr->nextPtr;
free(thisPtr);
thisPtr = thatPtr;
}
}
//得到最大值
int getMax(struct node *headPtr) {
struct node *thisPtr;
int max;
thisPtr = headPtr;
max = headPtr->data;
while (thisPtr != NULL) {
if (thisPtr->data > max) {
max = thisPtr->data;
}
thisPtr = thisPtr->nextPtr;
}
return max;
}
//得到最小值
int getMin(struct node *headPtr) {
struct node *thisPtr;
int min;
thisPtr = headPtr;
min = headPtr->data;
while (thisPtr != NULL) {
if (thisPtr->data < min) {
min = thisPtr->data;
}
thisPtr = thisPtr->nextPtr;
}
return min;
}
//得到和
int getSum(struct node *headPtr) {
struct node *thisPtr;
int sum;
thisPtr = headPtr;
sum = 0;
while (thisPtr != NULL) {
sum = sum + thisPtr->data;
thisPtr = thisPtr->nextPtr;
}
return sum;
}