Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- class LinkedList {
- private:
- struct ListNode {
- int value;
- ListNode *next;
- };
- public:
- ListNode *head, *tail;
- LinkedList();
- void add(int x);
- void print();
- ~LinkedList();
- };
- LinkedList::LinkedList() {
- this->head = nullptr;
- this->tail = nullptr;
- }
- LinkedList::~LinkedList() {
- while (head) {
- ListNode *head
- }
- }
- void LinkedList::add(int x) {
- ListNode *node = new ListNode{x, nullptr};
- if (!this->head) {
- this->head = node;
- this->tail = node;
- } else {
- this->tail->next = node;
- this->tail = this->tail->next;
- }
- }
- void LinkedList::print() {
- ListNode *current = head;
- while (current) {
- std::cout << current->value << " ";
- current = current->next;
- }
- std::cout << "\n";
- }
- LinkedList createList(int rest) {
- LinkedList list;
- for (int c, i = 0; i < rest; i++) {
- std::cin >> c;
- list.add(c);
- }
- return list;
- }
- LinkedList merge(const LinkedList &l1, const LinkedList &l2) {
- LinkedList merged;
- LinkedList tmp1 = l1;
- LinkedList tmp2 = l2;
- while (tmp1.head || tmp2.head) {
- if (tmp1.head && !tmp2.head) {
- merged.add(tmp1.head->value);
- tmp1.head = tmp1.head->next;
- } else if (!tmp1.head && tmp2.head) {
- merged.add(tmp2.head->value);
- tmp2.head = tmp2.head->next;
- } else if (tmp1.head && tmp2.head) {
- if (tmp1.head->value > tmp2.head->value) {
- merged.add(tmp2.head->value);
- tmp2.head = tmp2.head->next;
- } else {
- merged.add(tmp1.head->value);
- tmp1.head = tmp1.head->next;
- }
- } else {
- break;
- }
- }
- return merged;
- }
- int main() {
- int n, m;
- std::cin >> n >> m;
- LinkedList l1 = createList(n);
- LinkedList l2 = createList(m);
- LinkedList merged_list = merge(l1, l2);
- merged_list.print();
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement