Skip to content

Instantly share code, notes, and snippets.

@lsem
Created May 1, 2024 20:43
Show Gist options
  • Save lsem/6a33dae7b5f5630b21d7165878bc6237 to your computer and use it in GitHub Desktop.
Save lsem/6a33dae7b5f5630b21d7165878bc6237 to your computer and use it in GitHub Desktop.
merge_list.cpp
#include <iostream>
#include <string>
using namespace std;
struct Node {
Node *next = nullptr;
int value = 0;
};
struct List {
Node *head = nullptr, *tail = nullptr;
size_t size = 0;
void print() {
string sep = "";
for (auto p = head; p; p = p->next) {
cout << sep << p->value;
sep = ", ";
}
cout << " [" << this->size << "]\n";
}
void emplace_back(int v) {
if (head) {
assert(tail);
tail->next = new Node{};
tail->next->value = v;
tail = tail->next;
} else {
head = new Node{};
head->value = v;
tail = head;
}
size++;
}
void split_list(List &left_list, List &right_list) {
assert(size > 1);
// we have had and tail, and size.
Node *p = head;
Node *prev = nullptr;
for (size_t i = 0; i < this->size / 2; ++i) {
prev = p;
p = p->next;
}
cout << "DEBUG: p (middle): " << p->value << "\n";
cout << "DEBUG: p (prev(middle)): " << prev->value << "\n";
left_list.head = this->head;
left_list.tail = prev;
left_list.size = this->size / 2;
prev->next = nullptr;
right_list.head = p;
right_list.tail = this->tail;
right_list.size = this->size / 2;
if (this->size % 2 != 0) {
right_list.size++;
}
this->head = nullptr;
this->tail = nullptr;
this->size = 0;
}
void swap(List &l) {
std::swap(l.head, head);
std::swap(l.tail, tail);
std::swap(l.size, size);
}
void sort() {
if (this->size < 2) {
return;
}
List left, right;
split_list(left, right);
left.sort();
right.sort();
List merged;
auto take_into_merged = [&merged](Node *p) {
merged.emplace_back(p->value);
};
Node *p = left.head;
Node *q = right.head;
while (p && q) {
if (p->value < q->value) {
auto t = p->next;
take_into_merged(p);
p = t;
} else {
auto t = q->next;
take_into_merged(q);
q = t;
}
}
for (auto r = p ? p : q; r; r = r->next) {
take_into_merged(r);
}
swap(merged);
}
};
int main() {
List l;
l.emplace_back(4);
l.emplace_back(5);
l.emplace_back(3);
l.emplace_back(2);
l.emplace_back(1);
l.print();
l.sort();
l.print();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment