72 lines
1.0 KiB
C++
72 lines
1.0 KiB
C++
#include <iostream>
|
|
#pragma once
|
|
|
|
using namespace std;
|
|
|
|
namespace task4 {
|
|
|
|
struct Node
|
|
{
|
|
public:
|
|
int key;
|
|
Node* next;
|
|
};
|
|
|
|
Node* newNode(int key);
|
|
Node* list(int size, bool print);
|
|
int sum(Node* head);
|
|
|
|
int init()
|
|
{
|
|
setlocale(LC_ALL, "Russian");
|
|
int n; cout << "Введите длину: "; cin >> n;
|
|
|
|
Node* array = list(n, true);
|
|
cout << "Сумма: " << sum(array);
|
|
|
|
return 0;
|
|
}
|
|
|
|
Node* newNode(int key)
|
|
{
|
|
Node* node = new Node;
|
|
node->key = key;
|
|
node->next = nullptr;
|
|
return node;
|
|
}
|
|
|
|
Node* list(int size, bool print)
|
|
{
|
|
Node* head = newNode(1);
|
|
Node* last = newNode(2);
|
|
head->next = last;
|
|
|
|
for (int i = 0; i < size; i++)
|
|
{
|
|
Node* node = newNode(rand());
|
|
|
|
if (print) { cout << node->key << " "; }
|
|
|
|
last->next = node;
|
|
last = node;
|
|
}
|
|
if (print) { cout << endl; }
|
|
|
|
return head;
|
|
}
|
|
|
|
int sum(Node* head)
|
|
{
|
|
int sum = 0;
|
|
Node* ptr = head;
|
|
|
|
while (ptr)
|
|
{
|
|
sum = sum + ptr->key;
|
|
ptr = ptr->next;
|
|
}
|
|
|
|
return sum;
|
|
}
|
|
}
|