c++ - Why does it matter which pointer is changing the next element in a linked list? -


i have been working through hackerrank challenges. 1 reversing linked list. wanted try out recursively, think i've done well. however, code wasn't working correctly because of 1 tiny change:

void reverse(node *&head) {   if (head == null)       return;    node *link = head->next;    if (link == null)       return;     reverse(link);    link->next = head;    head->next = null;    head = link; } 

so wasn't working. traced problem first line after recursive call reverse(link), if change line head->next->next = head; program passes of tests. don't understand difference between link->next , head->next->next if consider link equal head->next. why matter pointer pointing head?

my logic:

given: -------------------------------------- h     l |     | [1]->[2]->[3] --------------------------------------   link->next = head; should   h    l  |    | [1]<-[2] [3]    head->next->next = head;   h   l  |   | [1]<-[2] [3]  because head->next-next == link->next 

is logic incorrect? have feeling has fact i'm recursively calling function passes reference. when trace out, don't see how makes difference in issue.

thanks

there tad mistake in logic.

if backtrack step-b-step form null becomes visible.

(assuming head reference , focusing on recursive algorithm.)

[h] = head [x] = null  [h] = [1]  [1] -> [2] -> [3] -> [x] // here link == null                       ^ 

pop 0 : function returns , previous function stack continues

now when return control @  [1] -> [2] -> [3] -> [x] // function returns previous call                ^ 

now next line is

link->next = head;   i.e. [3]->next = head; i.e.   [3] -> next = [h] i.e.   [3] -> [1]  head->next = null;  i.e.   [3] -> [1] -> [x]     head = link  i.e [h]=[3] 

pop 1

now function returns this

[2] -> [3] -> [1] -> [x] ^      [h] 

repeating same steps

link->next = head;   i.e. [2]->next = head; i.e.   [2] -> next = [h] i.e.   [2] -> [3]  head->next = null;  i.e.   [2] -> [3] -> [x]   // here lost access 1                            // since still in recurrsion stack                            // no problem  head = link  i.e [h]=[2] 

pop 2

now function returns this

[x]->[1]->[x]       ^ [2] -> [3] -> [x] [h] 

repeating same steps

link->next = head;   i.e. [1]->next = head; i.e.   [1] -> next = [h] i.e.   [1] -> [2] 

which correct far here comes error

head->next = null;   i.e.   [2] -> [x]   // here lost access [3] head = link  i.e [h]=[1] 

what linked list obtained here is

[1]->[2]->[x]     [x]->[3]->[x] [h]  ^ 

[3] leaked no access

pop 3 : final pop original function call

here link , head same i.e [1] , breaks down

link->next = head;   i.e. [1]->next = head; i.e.   [1] -> next = [h] i.e.   [1] -> [1]  head->next = null;  i.e.   [1] -> [x]   // here lost access [1] head = link [h]=[1] 

so have lost linked list

[1]->[x]   [x]->[2]->[x] [x]->[3]->[x] 

Comments