Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <string>
- struct Number {
- int* num;
- int* counter;
- explicit Number(int* num = new int(), int* counter = new int()) {
- this->num = num;
- this->counter = counter;
- }
- };
- struct Node {
- Number data;
- Node* p_next;
- explicit Node(Number& data, Node* p_next = nullptr) {
- this->data = data;
- this->p_next = p_next;
- }
- };
- struct List {
- List() : size_(0), head(nullptr), tail(nullptr) {
- }
- ~List() {
- clear();
- }
- bool empty() const {
- return (head == nullptr);
- }
- void pushBack(Number& value) {
- Node* new_node = new Node(value);
- if (head == nullptr) {
- head = new_node;
- } else {
- tail->p_next = new_node;
- }
- tail = new_node;
- ++size_;
- }
- void popFront() {
- Node* current = head;
- head = head->p_next;
- (*(current->data.counter))--;
- if (*(current->data.counter) == 0) {
- delete current->data.counter;
- delete current->data.num;
- }
- --size_;
- delete current;
- }
- void clear() {
- while (!empty()) {
- popFront();
- }
- head = nullptr;
- tail = nullptr;
- size_ = 0;
- }
- int& front() {
- return *(head->data.num);
- }
- const int& front() const {
- return *(head->data.num);
- }
- size_t size() const {
- return size_;
- }
- size_t size_;
- Node* head;
- Node* tail;
- };
- void print(List* list) {
- Node* current = list->head;
- while (current != nullptr) {
- std::cout << *(current->data.num) << " ";
- current = current->p_next;
- }
- std::cout << "\n";
- }
- List* merge(const List& a, const List& b) {
- List* new_list = new List();
- Node* first = a.head;
- Node* second = b.head;
- while (first != nullptr && second != nullptr) {
- if (*(first->data.num) <= *(second->data.num)) {
- new_list->pushBack(first->data);
- first = first->p_next;
- } else {
- new_list->pushBack(second->data);
- second = second->p_next;
- }
- }
- while (first != nullptr) {
- new_list->pushBack(first->data);
- first = first->p_next;
- }
- while (second != nullptr) {
- new_list->pushBack(second->data);
- second = second->p_next;
- }
- return new_list;
- }
- int main() {
- int n, m;
- std::cin >> n >> m;
- List a, b;
- for (size_t i = 0; i < n; ++i) {
- int x;
- std::cin >> x;
- int* new_num = new int(x);
- int* counter = new int(2);
- Number number = Number(new_num, counter);
- a.pushBack(number);
- }
- for (size_t i = 0; i < m; ++i) {
- int x;
- std::cin >> x;
- int* new_num = new int(x);
- int* counter = new int(2);
- Number number = Number(new_num, counter);
- b.pushBack(number);
- }
- List* answer = merge(a, b);
- print(answer);
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement