0

I am trying to sort nodes by their first element and I keep switching different nodes' first elements with other nodes second and third elements.

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

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

I am getting really confused comparing the pointers and making sense of the sort before printing. My display function:

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";
}
SergeyA
  • 61,605
  • 5
  • 78
  • 137
  • http://stackoverflow.com/questions/54142/how-does-the-comma-operator-work – SergeyA Oct 01 '15 at 18:01
  • 2
    What do you expect `ptr->x, ptr->y, ptr->z = s->x, s->y, s->z;` to do? And if you say it should do three assignments then you need to to go back to some basic tutorial again. – Some programmer dude Oct 01 '15 at 18:02

2 Answers2

0

It seems like you may have an issue with your fundamental understanding of assignment in C++. I'd recommend you review a little bit more about c++ just to get a better understanding.

The comma operator has the lowest precedence of any C operator, and acts as a sequence point.

Example:

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;

The above code actually looks like this if broken down:

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 has a good tutorial on it: https://en.wikipedia.org/wiki/Comma_operator#Syntax

Eissa
  • 700
  • 5
  • 17
0

You should try to write out your pointers on paper to make sense of them.

lnjblue
  • 140
  • 1
  • 13