0

The question is about this function which reverses a single linked list:

void  reverse(struct ListNode** head_ref)
{
    struct ListNode* prev = NULL;
    struct ListNode* current = *head_ref;
    struct ListNode* next = NULL;
    while (current != NULL) {
        next = current->next;
        current->next = prev;
        prev = current;
        current = next;
    }
    *head_ref = prev;
}

Why does the input have to be a double pointer, i tried to change it to a single pointer throughout the whole function but it does not work. Here is what i changed about it:

void  reverse(struct ListNode* head_ref)
{
    struct ListNode* prev = NULL;
    struct ListNode* current = head_ref;
    struct ListNode* next = NULL;
    while (current != NULL) {
        next = current->next;
        current->next = prev;
        prev = current;
        current = next;
    }
    head_ref = prev;
}

Since the new head is the "prev" pointer if you try to print it out inside the function it will properly give you its reverse but if you try to equal it to my single pointer of the head it does not work (in my knowledge equaling two pointers means making their address which they are pointing at equal) So what am I not getting ?

273K
  • 29,503
  • 10
  • 41
  • 64
Eno
  • 1
  • 1
  • See "passing by reference". You need to modify the `struct ListNode* head_ref` itself, so you pass it by reference. – aulven Aug 13 '22 at 16:42
  • Because in the second one the pointer is passed by value so the calling function would not see any change to that pointer. – drescherjm Aug 13 '22 at 16:42

0 Answers0