Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- using namespace std;
- struct Node { //односвязный список состоит из узлов
- int value; // узел хранит информативную часть
- Node* next; // и указатель на следующий узел в списке
- };
- class ForwardList {
- public:
- void Push_front(const int& value) {
- head = new Node{ value, head };
- size++;
- }
- void Pop_front() {
- if (size > 0) {
- Node* temp = head;
- head = head->next;
- delete temp;
- size--;
- }
- }
- void Print() {
- Node* temp = head;
- while (temp != nullptr) {
- cout << temp->value << " ";
- temp = temp->next;
- }
- cout << endl;
- }
- int Size() const {
- return size;
- }
- int Front() const {
- if (head != nullptr) {
- return head->value;
- }
- }
- void Insert(const int index, const int& value) {
- if (index == 0) {
- Push_front(value);
- return;
- }
- if (index > 0 && index < size) {
- Node* temp = head;
- for (int i = 0; i < index - 1; i++) {
- temp = temp->next;
- }
- temp->next = new Node{ value, temp->next };
- size++;
- }
- }
- void Erase(const int index) {
- if (index == 0) {
- Pop_front();
- return;
- }
- if (index > 0 && index < size) {
- Node* temp = head;
- for (int i = 0; i < index - 1; i++) {
- temp = temp->next;
- }
- Node* buf = temp->next->next;
- delete temp->next;
- temp->next = buf;
- size--;
- }
- }
- private:
- int size = 0;
- Node* head = nullptr;
- };
- int main() {
- ForwardList list1;
- for (int i = 0; i < 10; i++) {
- list1.Push_front(i + 1);
- list1.Print();
- }
- cout << list1.Size() << endl;
- for (int i = 0; i < 3; i++) {
- list1.Pop_front();
- list1.Print();
- }
- list1.Insert(2, 12);
- list1.Print();
- list1.Erase(3);
- list1.Print();
- cout << list1.Size() << endl;
- cout << list1.Front() << endl;
- }
Advertisement
Add Comment
Please, Sign In to add comment