我正在尝试按照第一个元素对节点进行排序,并且我不断切换不同的节点'第一个元素与其他节点的第二和第三个元素。
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";
}
答案 0 :(得分:0)
您可能对基本理解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
答案 1 :(得分:0)
你应该尝试在纸上写下你的指针以理解它们。