Given a singly linked list, find middle of the linked list and set middle node of the linked list at beginning of the linked list.
Input: 1 2 3 4 5 Output: 3 1 2 4 5 Input: 1 2 3 4 5 6 Output: 4 1 2 3 5 6
The idea is to first find middle of a linked list using two pointers, first one moves one at a time and second one moves two at a time. When second pointer reaches end, first reaches middle. We also keep track of previous of first pointer so that we can remove middle node from its current position and can make it head.
list before: 1 2 3 4 5 list After : 3 1 2 4 5
Time Complexity: O(n) when n is the total no of nodes in a linked list
Space Complexity: O(1) because using constant space
Please refer complete article on Make middle node head in a linked list for more details!
My Personal Notes arrow_drop_up
Please Login to comment...