链表按首字母排序
struct meta {
std::string music_name;
meta * next;
}mt;
// 初始化
void init(meta* &first, std::string *arr) {
meta * tail = first; // 尾指针
for (int i = 0; i < 10; i++) {
meta * tmp = new meta;
tmp->music_name = arr[i];
tail->next = tmp;
tail = tmp;
}
tail->next = nullptr;
first = first->next;
}
void show_meta(meta* first) {
std::cout << std::endl;
while (first) {
std::cout << first->music_name.c_str() << " ";
first = first->next;
}
}
int list_len(meta * first) {
int length = 0;
while (first) {
first = first->next;
length++;
}
return length;
}
// 合并两个链表
void sort(meta* first, int length) {
meta * head = new meta;
meta * bp = head;
meta * nbp;
if (!first|| !first->next) return;
meta * p = first->next;
meta * q = first, *tmp = first;
while (length-- > 0) {
while (p) {
if (strcmp(q->music_name.c_str(), p->music_name.c_str()) > 0) {
// 找到结点
q = p;
}
p = p->next;
}
// q 是first
if (q == first)
first = first->next;
else {
// 如果q不指向first,找q的前驱
tmp = first;
while (tmp->next != q)
tmp = tmp->next;
tmp->next = q->next;
}
bp->next = q;
bp = bp->next;
q->next = nullptr;
if (first) {
p = first->next;
q = first;
}
else {
p = nullptr;
q = nullptr;
}
}
// 循环结束
first = head->next;
delete head;
// show_meta(first);
}
int main(int argc, char ** argv) {
meta * first = new meta;
std::string arr[] = { "aa", "cc", "dd", "bb", "ee", "gg", "ff", "kk", "zz", "hh" };
init(first, arr);
show_meta(first);
sort(first, sizeof(arr)/ sizeof(arr[0]));
show_meta(first);
return 0;
}
附图(提纲):