BUPT-homework/semester2/pset2/1-linkedList.c

77 lines
1.2 KiB
C
Raw Normal View History

2022-03-14 19:54:02 +08:00
#include <stdio.h>
#include <stdlib.h>
typedef struct Node {
int data;
struct Node *next;
} Node;
Node *constructLinkedList();
Node *appendNode(Node *node, int data);
void deleteLinkedList(Node *head);
int main(void) {
Node *head = constructLinkedList();
int sum = 0, max, min;
max = head->data;
min = head->data;
while (head != NULL) {
if (head->data > max) {
max = head->data;
}
if (head->data < min) {
min = head->data;
}
sum += head->data;
head = head->next;
}
printf("The maximum,minmum and the total are:%d %d %d", max, min, sum);
deleteLinkedList(head);
return 0;
}
Node *constructLinkedList() {
int data;
scanf("%d", &data);
Node *head = malloc(sizeof(Node));
Node *ptr = head;
head->data = data;
head->next = NULL;
scanf("%d", &data);
while (data != -1) {
ptr = appendNode(ptr, data);
scanf("%d", &data);
}
return head;
}
Node *appendNode(Node *head, int data) {
Node *new = malloc(sizeof(Node));
new->data = data;
new->next = NULL;
head->next = new;
return new;
}
void deleteLinkedList(Node *head) {
if (head->next == NULL) {
free(head);
return;
} else {
deleteLinkedList(head->next);
free(head);
}
}