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

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.
Python3
class Node:
def __init__( self , data):
self .data = data
self . next = None
def setMiddleHead(head):
if (head = = None ):
return None
one_node = head
two_node = head
prev = None
while (two_node ! = None and
two_node. next ! = None ):
prev = one_node
one_node = one_node. next
two_node = two_node. next . next
prev. next = prev. next . next
one_node. next = head
head = one_node
return head
def push(head, new_data):
new_node = Node(new_data)
new_node. next = head
head = new_node
return head
def printList(head):
temp = head
while (temp! = None ):
print ( str (temp.data), end = " " )
temp = temp. next
print ("")
head = None
for i in range ( 5 , 0 , - 1 ):
head = push(head, i)
print ( " list before: " , end = "")
printList(head)
head = setMiddleHead(head)
print ( " list After: " , end = "")
printList(head)
|
Output:
list before: 1 2 3 4 5
list After : 3 1 2 4 5
Time complexity: O(n) where n is the size of the linked list
Space Complexity: O(1) since using constant space
Please refer complete article on Make middle node head in a linked list for more details!