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.
@rachel418 The last element of a Linked list is that element whose next is equal to null, alright?
So in order to reverse the linked list,
1. Firstly, we reverse the direction of 'next' of each node.
2. Secondly, we make the next of old head element point to null, so that now it becomes the last element. Now don't get confused why it's still called as 'head' in the code! That's just a name which we are using to refer to variables.
Observe that in the last diagram, 'remaining' is pointing to 3, and the 'next' of 3 points to 2 and the next of 2 point to 1 and the next of 1 points to null. Bingo! Turns out last element now, is 1, which was earlier the first element.
Earlier the linked list was, 1 is the first element, next of 1 points to 2, next of 2 points to 3 and 3 pointed to null, 3 was the last element.
Now the pointer called 'remaining' is pointing to three, in the last diagram, remaining is the new head, and 'remaining' is returned as a result.
@nitin2n33 explained in great detail how this recursion is taking place -> recursion stacks
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 →
@rachel418 The last element of a Linked list is that element whose next is equal to null, alright?
So in order to reverse the linked list,
1. Firstly, we reverse the direction of 'next' of each node.
2. Secondly, we make the next of old head element point to null, so that now it becomes the last element. Now don't get confused why it's still called as 'head' in the code! That's just a name which we are using to refer to variables.
Observe that in the last diagram, 'remaining' is pointing to 3, and the 'next' of 3 points to 2 and the next of 2 point to 1 and the next of 1 points to null. Bingo! Turns out last element now, is 1, which was earlier the first element.
Earlier the linked list was, 1 is the first element, next of 1 points to 2, next of 2 points to 3 and 3 pointed to null, 3 was the last element.
Now the pointer called 'remaining' is pointing to three, in the last diagram, remaining is the new head, and 'remaining' is returned as a result.
@nitin2n33 explained in great detail how this recursion is taking place -> recursion stacks