Skip to content
Related Articles
Get the best out of our app
GeeksforGeeks App
Open App

Related Articles

Python Program For Making Middle Node Head In A Linked List

Improve Article
Save Article
Like Article
Improve Article
Save Article
Like Article

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. 


# Python3 program to make middle node
# as head of Linked list
# Linked List node
class Node:
    def __init__(self, data): = data = None
# function to get the middle node
# set it as the beginning of the
# linked list
def setMiddleHead(head):
    if(head == None):
        return None
    # To traverse nodes
    # one by one
    one_node = head
    # To traverse nodes by
    # skipping one
    two_node = head
    # To keep track of previous middle
    prev = None
    while(two_node != None and
 != None):
        # For previous node of middle node
        prev = one_node
        # Move one node each time
        one_node =
        # Move two nodes each time
        two_node =
    # Set middle node at head = = head
    head = one_node
    # Return the modified head
    return head
def push(head, new_data):
    # Allocate new node
    new_node = Node(new_data)
    #Link the old list to new node = head
    # Move the head to point the new node
    head = new_node
    # Return the modified head
    return head
# A function to print a given linked list
def printList(head):
    temp = head
    while (temp!=None):
        print(str(, end = " ")
        temp =
# Create a list of 5 nodes
head = None
for i in range(5, 0, -1):
    head = push(head, i)
print(" list before: ", end = "")
head = setMiddleHead(head)
print(" list After: ", end = "")
# This code is contributed by Pranav Devarakonda


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!

My Personal Notes arrow_drop_up
Last Updated : 19 Jul, 2022
Like Article
Save Article
Similar Reads
Related Tutorials