+ 5

How to reverse liked list ?

This question is taken from interview questions.

28th Mar 2018, 8:00 PM
Soft_aditya
Soft_aditya - avatar
3 Answers
+ 6
Here's one way to do it: If you're doing Java, use the method 'addFirst' so the following occurs (Or any similar method in other languages): -> [0] -> null (Add 3) -> [3] -> [0] -> null - The node you add points to what the top pointed to, then the top points to the new node. So, the last thing you add is the first thing in the list. Now, * Create new temporary list * Traverse through your old list * As you traverse, add the item to the temporary list Lets say this is our list: -> [2] -> [6] -> null We make a new list: -> null Now, traverse the old list & add to the new one. The top points to 2, Add 2: -> [2] -> null 2 points to 6, Add 6: -> [6] -> [2] -> null Voila. We now have the list in reverse order!
28th Mar 2018, 8:58 PM
Rrestoring faith
Rrestoring faith - avatar
+ 2
In c++ you can easily traverse it in reverse order. Just use rbegin and rend. But keep in mind that you still need to use the increment operator on the iterator and not decrement, which feels a bit more fitting for reverse traversing. https://code.sololearn.com/crsMwiq8s0L2/?ref=app
29th Mar 2018, 3:51 AM
Alex
Alex - avatar
0
Can you give me with javascript
29th Dec 2020, 1:11 AM
Biso