-2

I have written a simple reverse function for the linked list, shown below:

typedef struct _NODE
{
    int data;
    _NODE *next;

}NODE;

void print(NODE *head)
{
    NODE *start;
    start = head;
    while (start)
    {
        printf("%d ", start->data);
        start = start->next;
    }
}
NODE* reverse(NODE *head)
{
    NODE *prev = NULL;
    NODE *curr = head;

    while (curr)
    {
        NODE *temp = curr->next;
        curr->next = prev;
        prev = curr;
        curr = temp;
    }
    head = prev;

    return head;

}
int main()
{
    NODE *head = new NODE;
    NODE *node1 = new NODE;
    NODE *node2 = new NODE;

    head->data = 1;
    node1->data = 2;
    node2->data = 3;

    head->next = node1;
    node1->next = node2;
    node2->next = NULL;

    reverse(head);

    print(head);


    getchar();

    delete head;
    delete node1;
    delete node2;
    head = NULL;
    node1 = NULL;
    node2 = NULL;

    return 1;

}

I found the output will always be 1. My question is why does the head pointer after the reverse function always point to the node with value 1. I have already assigned the previous pointer to the head pointer in the reverse function.

But if I change below, the output became correct.

reverse(head);

To

head = reverse(head); 
Pranav Kasetti
  • 8,770
  • 2
  • 50
  • 71
ted
  • 1
  • 4
    [What's the difference between passing by reference vs. passing by value?](https://stackoverflow.com/a/430958) – 001 Sep 24 '20 at 11:57
  • 2
    If you wrote this code then surely you have an idea why `reverse` was written to return a value. – kaylum Sep 24 '20 at 11:59
  • 1
    The function returns the new head. It does not (cannot) modify the value of the variable whose value you passed to it. (There is nothing special about pointers.) – molbdnilo Sep 24 '20 at 12:07
  • You can change the name of the parameter in reverse to head_copy – stark Sep 24 '20 at 12:32
  • `_NODE` identifier is reserved to the language implementation. You should rename your class. How about `ಠ_ಠNode`? – eerorika Sep 24 '20 at 13:15

1 Answers1

1

Because the head variable in the reverse function is not the same variable as the head variable in the main function.

Assigning to the head variable in reverse does not change the value of the head variable in main.

john
  • 85,011
  • 4
  • 57
  • 81