对包含多个元素的节点的链表进行排序



我试图按节点的第一个元素排序,我不断切换不同节点的第一个元素与其他节点的第二和第三个元素。

<>之前我的目标:1,1,1 -> 2,2,2 -> null我的实际结果是: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

你应该试着把你的指针写在纸上,让它们有意义。

相关内容

  • 没有找到相关文章

最新更新