Challenge: Build and Show a Linked List

Lab C++ Beginner 10 points

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
Sample input available Sample output available
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
HOME LABS COMMUNITY DASHBOARD