Files
ARPZ_s1_pr6/task8.h

114 lines
1.8 KiB
C++

#include <iostream>
using namespace std;
#pragma once
namespace task8 {
struct Node
{
public:
int key;
Node* next;
};
Node* newNode(int key); //ñîçäàåò óçåë
Node* rand_list(int size); //ñîçäàåò ñïèñîê
void print_list(Node* head); //ïèøåò ýëåìåíòû ñïèñêà
void cycle(Node*&head, int offset); //ñìåùàåò ýëåìåíòû â ñïèñêå öèêëè÷åñêè
int init()
{
int n; cout << "Enter size: "; cin >> n;
Node* lst = rand_list(n);
print_list(lst);
int offset; cout << "Enter offset: "; cin >> offset;
cycle(lst, offset);
print_list(lst);
return 0;
}
Node* newNode(int key)
{
Node* node = new Node;
node->key = key;
node->next = nullptr;
return node;
}
Node* rand_list(int size)
{
Node* head = newNode(rand());
Node* last = newNode(rand());
head->next = last;
for (int i = 0; i < size; i++)
{
Node* node = newNode(i+1);
last->next = node;
last = node;
}
return head->next->next;
}
void push_back(Node* head, int key)
{
Node* last = nullptr;
Node* ptr = head;
while (ptr)
{
last = ptr;
ptr = ptr->next;
}
ptr = newNode(key);
last->next = ptr;
}
Node* push_forward(Node* head, int key)
{
Node* node = newNode(key);
node->next = head;
return node;
}
void print_list(Node* head)
{
Node* ptr = head;
while (ptr)
{
cout << ptr->key << " -> ";
ptr = ptr->next;
}
cout << "nullptr" << endl;
}
void cycle(Node*& head, int offset)
{
int amt = 0;
Node* ptr = head;
while (ptr->next)
{
ptr = ptr->next;
amt++;
}
ptr->next = head;
Node* prv = ptr;
if (offset < 0)
{
offset = abs(amt+1 + offset);
}
for (int i = 0; i < offset; i++)
{
prv = prv->next;
head = head->next;
}
prv->next = nullptr;
}
}