Dear reader, I hope you enjoy solving these problems. This problem is very similar to the previous one, except we are going to approach it differently.
Important Links :Problem Link, Question Video, Solution Video
Dear reader, I hope you enjoy solving these problems. This problem is very similar to the previous one, except we are going to approach it differently.
Important Links :Problem Link, Question Video, Solution Video
If you face any difficulty understanding the problem, watch the Question video.
So, if your linked list was initially something like this:
After reversing the Linked List by changing only the pointers we should have:
If you notice carefully all we have done is reversed the pointers, now the next node is storing the address of the prev node, and so on.
All we need to do is change the current node next to the previous one. But if we do that, how shall we move to the next node? Because right now next is pointing to the previous, so we will have to keep a temporary backup of the next node, before updating the data.
So initially we will have two pointers, prev, and cur. prev will be null and cur will be head. We will also have a temp variable to store the next node. Basically, before doing anything to prev and cur, we will do:
temp = cur.next
Now we can do,
cur.next = prev
prev = cur
cur = temp
So, after this operation it will look like this:
We will again store the next pointer in temp.
temp = curr.next
Now we can do the reversing part,
cur.next = prev
prev = cur
cur = temp
Clearly, we can see that the first two nodes have been reversed, we can continue this as long as cur doesn't reach null.
After the linked list has been reversed we need to swap the head and tail.
If you faced any difficulty in this part, watch the video. If you have understood, try to write the code by yourself.
java; true";
O(n)
This is a much more efficient approach compared to the previous one where we dealt with data. Here we are just running a linear loop, so the time complexity is O(n).
O(1)
We are not using any auxiliary space, hence the space complexity is O(1).
I hope you have understood the problem and the explanation. If you have some doubts I would insist you watch the solution video. And try to dry run the code, this will make everything clear. See you in the next problem.