+ 5
How to reverse liked list ?
This question is taken from interview questions.
3 odpowiedzi
+ 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!
+ 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
0
Can you give me with javascript