Files
ARPZ_s1_pr6/task4.h

69 lines
1.1 KiB
C++

#include <iostream>
#pragma once
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;
}
}