Intuition
From the description of this question, we need three steps to achieve the reorder
operation for a singly linked list:
- seperate the list into two parts
- reverse the right part
- merge the left part and reversed right part one by one
Algorithm
1. seperate the list into two parts
A stright and simple method is counting the node number and find the middle one. This will cost O(n) time.
2. reverse the right part
There are two methods for reversing the list, recursion and pointers. We are all familiar with the prons and cons of recursion. It’s easy to be implemented and understood, but the size of the list are limited by the size of stack frame. The time complexity for reversing a list is still O(n).
To be honest, I can’t resist the temptation of recursion, it’s brief and concise. Sometimes recursion is like a magic, we suppose it works for some case and then deduce the relationship between the past and the future, finally we solved the whole problem, it’s always a little unrealistic. We can call this method mathematical induction. Maybe when quantum computer comes out, this method will not be limited by the problem size and can be first choice of different solutions.
3. merge the left part and reversed right part one by one
We just combine two list one by one, for example 1->2->3
and 5->4
will be 1-> 5 ->2-> 4 ->3
after merge. Time complexity is still O(n).
Code
1 | /** |
Comlexity
Time Complexity: O(n), see analysis above.
Space Complexity: We cost a constant space O(1) if using pointer method to reverse a list, other wise it’s O(n)