![]() |
VOOZH | about |
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.
Examples:
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
👁 https://media.geeksforgeeks.org/wp-content/uploads/Capturedsdw.png
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.
Implementation:
list before: 1 2 3 4 5 list After: 3 1 2 4 5
Time Complexity : O(n)
Auxiliary Space : O(1)