如何在 C++ 中使用一个变量对由两部分组成的链表进行排序?

How to sort a two-part linked list using one variable in C++?

我正在尝试创建一个列出人名及其出生年份的链表。此列表应在输入后按出生年份升序排序。到目前为止,我已经按年份对列表进行了排序,这正是我想要的——但我不知道如何在排序顺序更改时移动名称。

节点class定义如下:

class node
{
public:
    string name, value;
    int year;
    node *Next;
}
*head = NULL, *tail = NULL;

使用以下 void 函数对输入进行升序排序:

void sort (node *head)
{
    while (head)
    {
        node *min = head;
        node *cur = head -> Next;
        while (cur)
        {
            if ((min -> year) > (cur -> year))
            {
                min = cur;
            }
            cur = cur -> Next;
        }
        int x = head -> year;
        head -> year = min -> year;
        min -> year = x;
        head = head -> Next;
    }
}

并使用另一个void函数输出到屏幕:

void print (node *x)
{
    if (x == NULL)
    {
        return;
    }
    node *cur = x;
    while (cur)
    {
        cout << cur -> name << " (" << cur -> year << ")\n";
        cur = cur -> Next;
    }
    cout << endl;
}

在上面的代码中,year指的是出生年份,name指的是人名。这是个问题,因为如果我输入“Person 1”是 2000 年出生的人,Person 2 是 1995 年出生的人,那么输出结果会是 Person 1 出生于 1995 年,Person 2 出生于 2000 年。排序。有没有办法用名字对年份进行排序?

在交换year的同时也应该交换name

您可以使用 std::swap 交换变量而不使用临时变量。

#include <algorithm>

void sort (node *head)
{
    while (head)
    {
        node *min = head;
        node *cur = head -> Next;
        while (cur)
        {
            if ((min -> year) > (cur -> year))
            {
                min = cur;
            }
            cur = cur -> Next;
        }
        std::swap(head -> year, min -> year);
        std::swap(head -> name, min -> name);
        // you may also want this
        // std::swap(head -> value, min -> value);
        head = head -> Next;
    }
}