Challenge: Build and Show a Linked List
Completed
Read n numbers, build a linked list (adding each at the end), print it as a -> b -> c -> nullptr, then the sum of its values on the next line (computed by walking the list).
Input
Line 1: n (n ≥ 1). Line 2: n whole numbers.
Output
a -> ... -> nullptr Sum: <sum>
Example
Input
3 3 1 4
Output
3 -> 1 -> 4 -> nullptr Sum: 8
Editor
C++
Hints
Keep a tail pointer so adding at the end is O(1).
Walk with for (Node* c = head; c; c = c->next).
Solution explanation
With a tail pointer, building the list is O(n) in total.
Show solution
#include <iostream>
using namespace std;
struct Node {
int value;
Node* next;
Node(int v) : value(v), next(nullptr) {}
};
int main() {
int n;
cin >> n;
Node* head = nullptr;
Node* tail = nullptr;
for (int i = 0; i < n; i++) {
int x;
cin >> x;
Node* node = new Node(x);
if (!head) head = tail = node;
else { tail->next = node; tail = node; }
}
long long sum = 0;
for (Node* c = head; c; c = c->next) {
cout << c->value << " -> ";
sum += c->value;
}
cout << "nullptr" << endl;
cout << "Sum: " << sum << endl;
return 0;
} Output
Answer
You can practice without logging in. Log in to save completion.
Save your progress
You're practising as a guest, so your progress won't be saved.
- Track every lab you complete
- Earn verifiable lab certificates
- See your progress in every module