We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
That's because, we want to keep remaining unchanged!
If you do remaining.next = head and return remaining, then remaining will keep changing its pointing to the next element, until the recursion fully pops and in the end remaining.next will point to the 1st element, rendering only 2 elements in the list.
Eg:
1->2->3->4
When head = 3 and remaining = 4, remaining.next = head will change to
1->2->3<-4
Now still remaining =4, but in the subsequent recursion pop, head will change to 2
Now when that happens and you do remaining.next = head, then remaining.next will now point to 2. ie 4 will point to 2. This will happen until 4 will point to 1 and the list will only have 2 elements.
However, if you wish this doesn't happen, then before returning remaining you could do something like remaining.next = remaining. But then the last pop of recursion would now return the 1st element as head and the list wouldn't be reversed.
Therefore, remaining shouldn't be changed!
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Reverse a linked list
You are viewing a single comment's thread. Return to all comments →
That's because, we want to keep remaining unchanged!
If you do remaining.next = head and return remaining, then remaining will keep changing its pointing to the next element, until the recursion fully pops and in the end remaining.next will point to the 1st element, rendering only 2 elements in the list.
Eg:
1->2->3->4
When head = 3 and remaining = 4, remaining.next = head will change to
1->2->3<-4
Now still remaining =4, but in the subsequent recursion pop, head will change to 2
Now when that happens and you do remaining.next = head, then remaining.next will now point to 2. ie 4 will point to 2. This will happen until 4 will point to 1 and the list will only have 2 elements.
However, if you wish this doesn't happen, then before returning remaining you could do something like remaining.next = remaining. But then the last pop of recursion would now return the 1st element as head and the list wouldn't be reversed.
Therefore, remaining shouldn't be changed!