Store numbers in a linked list in the order they arrive, then walk the list to count and add them.
What to build
A linked list built by appending, and one traversal that measures it.
Requirements
- Append each number at the end of the list, using a tail pointer.
- Print the values in order on the first line, or
emptyfor an empty list. - Print the number of nodes and the sum of the values on the second line.
Input
The first line has n. The second line has the n numbers.
Output
Two lines: the list, then the count and the sum.
Constraints
0 ≤ n ≤ 100.
Example
Input:
3
4 7 1
Output:
4 7 1
3 12
Why it works
A linked list has no index and no stored length, so counting or adding means following next from the head until NULL.
Examples
Example 1 · Input
3 4 7 1
Expected output
4 7 1 3 12
Example 2 · Input
1 -5
Expected output
-5 1 -5
Hints
Hint 1
For each number, malloc a node, set its next to NULL, and link it after the tail.
Hint 2
The first node is special: both head and tail must point to it.
Hint 3
Walk the list with for (Node *p = head; p != NULL; p = p->next).
Solution
Show one correct solution (try it yourself first)
#include <stdio.h>
#include <stdlib.h>
typedef struct node {
int value;
struct node *next;
} Node;
int main(void) {
int n;
scanf("%d", &n);
Node *head = NULL, *tail = NULL;
for (int i = 0; i < n; i++) {
Node *p = malloc(sizeof(Node));
scanf("%d", &p->value);
p->next = NULL;
if (head == NULL) head = p;
else tail->next = p;
tail = p;
}
int count = 0, sum = 0;
if (head == NULL) printf("empty");
for (Node *p = head; p != NULL; p = p->next) {
if (p != head) printf(" ");
printf("%d", p->value);
count++;
sum += p->value;
}
printf("\n%d %d\n", count, sum);
while (head != NULL) {
Node *next = head->next;
free(head);
head = next;
}
return 0;
}