Linked List with unique_ptr
Completed
Build a singly linked list of n integers where each node owns the next through unique_ptr<Node> (insert at the front). Print the values and their sum.
Input
Line 1: n. Line 2: n integers.
Output
Two lines.
Example
Input
4 1 2 3 4
Output
4 3 2 1 10
Editor
C++
Hints
Ownership is transferred with std::move.
.get() gives a plain pointer for walking the list without taking ownership.
Solution explanation
When the head is destroyed, every node is freed automatically.
Show solution
#include <iostream>
#include <memory>
using namespace std;
struct Node {
int value;
unique_ptr<Node> next;
};
int main() {
int n;
cin >> n;
unique_ptr<Node> head;
for (int i = 0; i < n; i++) {
auto node = make_unique<Node>();
cin >> node->value;
node->next = move(head);
head = move(node);
}
long long sum = 0;
for (Node *p = head.get(); p != nullptr; p = p->next.get()) {
cout << p->value << " ";
sum += p->value;
}
cout << "\n" << sum << "\n";
return 0;
}