Make middle node head in a linked list
- Difficulty Level : Easy
- Last Updated : 19 Jul, 2022
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)
Auxiliary Space : O(1)
This article is contributed by R_Raj. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.