One solution is toiterate the nodes in original order and move them to the head of the list one by one. It seems hard to understand. We will first use an example to go through our algorithm.
Algorithm Overview
Let's look at an example:
Keep in mind that the black node 23 is our original head node.
First, we move the next node of the black node, which is node 6, to the head of the list:
Then we move the next node of the black node, which is node 15, to the head of the list:
The next node of the black node now is null. So we stop and return our new head node 15.
More
In this algorithm, each node will be movedexactly once.
Therefore, the time complexity isO(N), where N is the length of the linked list. We only use constant extra space so the space complexity isO(1).
This problem is the foundation of many linked-list problems you might come across in your interview. If you are still stuck, our next article will talk more about the implementation details.
There are also many other solutions. You should be familiar with at least one solution and be able to implement it.