Untitled
unknown
plain_text
2 years ago
2.7 kB
6
Indexable
#include <iostream> template <typename T> struct Node { T data; Node* next; }; template <typename T> class List { private: Node<T>* _head; int _size = 0; public: List() { _head = nullptr; }; void push(T val) { // добавление в конец _size++; if (_head == nullptr) { _head = new Node<T>(); _head->data = val; return; } Node<T>* temp = _head; while (temp->next) { temp = temp->next; } Node<T>* n = new Node<T>(); n->data = val; n->next = nullptr; temp->next = n; }; T pop() { // удаление с конца if (_head) { T p = _head->data; _head = _head->next; _size--; return p; } }; void set_value(int idx, T value) { Node<T>* temp = _head; int index = 0; while (temp->next) { if (index == idx) { temp->data = value; return; } else { temp = temp->next; } index++; } temp->data = value; }; T& operator[](const int index) { int counter = 0; Node<T>* current = this->_head; while (current != nullptr) { if (counter == index) { return current->data; } current = current->next; counter++; } } void print_data() { Node<T>* temp = _head; while (temp->next) { std::cout << temp->data << " "; temp = temp->next; } if (temp != nullptr) std::cout << temp->data << std::endl; }; int GetSize() { return _size; } Node<T>* merge(Node<T>* head1, Node<T>* head2) { Node<T>* result = NULL; if (head1 == NULL) { return head2; } if (head2 == NULL) { return head1; } if (head1->data > head2->data) { result = head1; result->next = merge(head1->next, head2); } else { result = head2; result->next = merge(head1, head2->next); } return result; } void sort(List<T>& lst1, List<T>& lst2) { Node<T>* h1 = lst1._head; Node<T>* h2 = lst2._head; _head = merge(h1, h2); _size = lst1.GetSize() + lst2.GetSize(); } }; int main() { setlocale(LC_ALL, "ru"); int n; int f; List<int> lst3; List<int> lst; List<int> lst2; std::cout << "Введите размер двух списков " << std::endl; std::cin >> n; for (int i = 0; i < n; i++) { std::cin >> f; lst.push(f); } for (int i = 0; i < n; i++) { std::cin >> f; lst2.push(f); } for (int i = 0; i < lst.GetSize(); i++) { std::cout << lst[i] << " "; } std::cout << std::endl; for (int i = 0; i < lst2.GetSize(); i++) { std::cout << lst2[i] << " "; } lst3.sort(lst, lst2); std::cout <<std::endl; for (int i = 0; i < lst3.GetSize(); i++) { std::cout << lst3[i]; } return 0; };
Editor is loading...