对具有多个元素节点的链表进行排序

Sorting a linked list with nodes of multiple elements

我正在尝试按节点的第一个元素对节点进行排序,并且我一直在将不同节点的第一个元素与其他节点的第二个和第三个元素进行切换。

My goal: 
1, 1, 1 -> 2, 2, 2 -> NULL

My actual outcome:
1, 2, 2 -> 2, 1, 1-> NULL

我真的很困惑比较这些指针并在打印之前理解排序。我的显示函数:

void display()
{
    struct node *s, *ptr;
    int value;
    if (start == NULL)
    {
        cout<<"Try Again";
    }

    ptr = head;
    cout<<"Elements of list are: ";
    while (ptr != NULL)
    {
        for (s = ptr->next; s !=NULL; s = s->next)
        {
            if (ptr->x > s->x)
            {
                value = ptr->x, ptr->y, ptr->z;
                ptr->x, ptr->y, ptr->z = s->x, s->y, s->z;
                s->x, s->y, s->y = value;
            }
            cout<< ptr->x <<", "<< ptr->y <<", "<<ptr->z << " -> ";
        }
        ptr = ptr->next;
    }
    cout<<"NULL";
}

看来您对 C++ 赋值的基本理解有问题。我建议您多了解一下 C++,以便更好地理解。

逗号运算符在所有 C 运算符中具有最低的优先级,并充当序列点。

示例:

value = ptr->x, ptr->y, ptr->z;
ptr->x, ptr->y, ptr->z = s->x, s->y, s->z;
s->x, s->y, s->y = value;

上面的代码如果分解的话实际上是这样的:

value = ptr->x; // Assignment occurring and the other ptr's following the first comma are being discarded

ptr->z = s->x; // Assignment occurring and the other ptr's following the first comma are being discarded

s->y = value; // Assignment occurring and the other ptr's following the first comma are being discarded

Wiki 上有很好的教程:https://en.wikipedia.org/wiki/Comma_operator#Syntax

您应该尝试将您的指示写在纸上以理解它们。