Hướng giải của Gộp hai danh sách


Nhớ rằng hướng dẫn giải này chỉ nên sử dụng khi bế tắc, và tuyệt đối không nên sao chép mã nguồn kèm theo. Hãy tôn trọng tác giả bài tập và người viết hướng dẫn giải.
Nộp mã nguồn lời giải chính thức trước khi giải bài tập đó có thể khiến bạn bị ban.
Lời giải

Dùng hai con trỏ để duyệt hai danh sách, chọn phần tử nhỏ hơn để thêm vào danh sách kết quả.

#include <bits/stdc++.h>
using namespace std;

struct Node {
    int data;
    Node* next;
    Node(int val) : data(val), next(nullptr) {}
};

int main() {
    int n, m;
    cin >> n;
    Node *h1 = nullptr, *t1 = nullptr;
    for (int i = 0; i < n; ++i) {
        int x; cin >> x;
        Node* node = new Node(x);
        if (!h1) h1 = t1 = node;
        else t1->next = node, t1 = node;
    }
    cin >> m;
    Node *h2 = nullptr, *t2 = nullptr;
    for (int i = 0; i < m; ++i) {
        int x; cin >> x;
        Node* node = new Node(x);
        if (!h2) h2 = t2 = node;
        else t2->next = node, t2 = node;
    }
    Node dummy(0), *tail = &dummy;
    while (h1 && h2) {
        if (h1->data < h2->data) {
            tail->next = h1; h1 = h1->next;
        } else {
            tail->next = h2; h2 = h2->next;
        }
        tail = tail->next;
    }
    tail->next = h1 ? h1 : h2;
    for (Node* p = dummy.next; p; p = p->next) {
        cout << p->data;
        if (p->next) cout << " -> ";
    }
}
class Node:
    def __init__(self, val):
        self.data = val
        self.next = None

n = int(input())
a = list(map(int, input().split()))
m = int(input())
b = list(map(int, input().split()))

h1 = t1 = None
for val in a:
    node = Node(val)
    if h1 is None: h1 = t1 = node
    else: t1.next = node; t1 = node

h2 = t2 = None
for val in b:
    node = Node(val)
    if h2 is None: h2 = t2 = node
    else: t2.next = node; t2 = node

dummy = Node(0)
tail = dummy
while h1 and h2:
    if h1.data < h2.data:
        tail.next = h1; h1 = h1.next
    else:
        tail.next = h2; h2 = h2.next
    tail = tail.next
tail.next = h1 or h2

p = dummy.next
while p:
    print(p.data, end='')
    if p.next:
        print(' -> ', end='')
    p = p.next

Nhận xét

Không có ý kiến tại thời điểm này.