Open In App

Python program to find middle of a linked list using one traversal

Last Updated : 23 Apr, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Given a singly linked list, find the middle of the linked list. Given a singly linked list, find the middle of the linked list. For example, if the given linked list is 1->2->3->4->5 then the output should be 3.

Method 1: Traverse the whole linked list and count the no. of nodes. Now traverse the list again till count/2 and return the node at count/2. 

Python3




# Python program for the above approach
class Node:
    def __init__(self, data):
        self.data = data
        self.next = None
 
 
class NodeOperation:
    # Function to add a new node
    def pushNode(self, head_ref, data_val):
 
        # Allocate node and put in the data
        new_node = Node(data_val)
 
        # Link the old list of the new node
        new_node.next = head_ref
 
        # move the head to point to the new node
        head_ref = new_node
        return head_ref
 
    # A utility function to print a given linked list
    def printNode(self, head):
        while (head != None):
            print('%d->' % head.data, end="")
            head = head.next
        print("NULL")
 
    ''' Utility Function to find length of linked list '''
 
    def getLen(self, head):
        temp = head
        len = 0
 
        while (temp != None):
            len += 1
            temp = temp.next
 
        return len
 
    def printMiddle(self, head):
        if head != None:
            # find length
            len = self.getLen(head)
            temp = head
 
            # traverse till we reached half of length
            midIdx = len // 2
            while midIdx != 0:
                temp = temp.next
                midIdx -= 1
 
            # temp will be storing middle element
            print('The middle element is: ', temp.data)
 
 
# Driver Code
head = None
temp = NodeOperation()
head = temp.pushNode(head, 5)
head = temp.pushNode(head, 4)
head = temp.pushNode(head, 3)
head = temp.pushNode(head, 2)
head = temp.pushNode(head, 1)
temp.printNode(head)
temp.printMiddle(head)
 
# This code is contributed by Yash Agarwal


Output

1->2->3->4->5->NULL
The middle element is:  3

Time Complexity: O(n) where n is no of nodes in linked list
Auxiliary Space: O(1)

Method 2: Traverse linked list using two pointers. Move one pointer by one and another pointer by two. When the fast pointer reaches the end slow pointer will reach middle of the linked list. 

Implementation:

Python3




# Python 3 program to find the middle of a 
# given linked list
 
# Node class
class Node:
 
    # Function to initialise the node object
    def __init__(self, data):
        self.data = data
        self.next = None
 
class LinkedList:
 
    def __init__(self):
        self.head = None
 
    def push(self, new_data):
        new_node = Node(new_data)
        new_node.next = self.head
        self.head = new_node
 
    # Function to get the middle of
    # the linked list
    def printMiddle(self):
        slow_ptr = self.head
        fast_ptr = self.head
 
        if self.head is not None:
            while (fast_ptr is not None and fast_ptr.next is not None):
                fast_ptr = fast_ptr.next.next
                slow_ptr = slow_ptr.next
            print("The middle element is: ", slow_ptr.data)
 
# Driver code
list1 = LinkedList()
list1.push(5)
list1.push(4)
list1.push(2)
list1.push(3)
list1.push(1)
list1.printMiddle()


Output

The middle element is:  2

Time Complexity: O(N) where N is the number of nodes in Linked List.

Auxiliary Space: O(1)

 

Method 3: Initialized the temp variable as head Initialized count to Zero Take loop till head will become Null(i.e end of the list) and increment the temp node when count is odd only, in this way temp will traverse till mid element and head will traverse all linked list. Print the data of temp. 

Implementation:

Python3




# Python 3 program to find the middle of a
# given linked list
 
class Node:
    def __init__(self, value):
        self.data = value
        self.next = None
     
class LinkedList:
 
    def __init__(self):
        self.head = None
 
    # create Node and make linked list
    def push(self, new_data):
        new_node = Node(new_data)
        new_node.next = self.head
        self.head = new_node
         
    def printMiddle(self):
        temp = self.head
        count = 0
         
        while self.head:
 
            # only update when count is odd
            if (count & 1):
                temp = temp.next
            self.head = self.head.next
 
            # increment count in each iteration
            count += 1
         
        print(temp.data)   
         
# Driver code
llist = LinkedList()
llist.push(1)
llist.push(20)
llist.push(100)
llist.push(15)
llist.push(35)
llist.printMiddle()
# code has been contributed by - Yogesh Joshi


Output

100

Complexity Analysis:

  • Time complexity: O(N) where N is the size of the given linked list
  • Auxiliary Space: O(1) because it is using constant space

METHOD 4:Using a list to store elements

APPROACH:

The above Python code implements a program that finds the middle element of a linked list using a single traversal. It defines two classes: Node and LinkedList. Node class has two instance variables: data and next. LinkedList class has an instance variable head which points to the first node of the linked list.

ALGORITHM:

1.Initialize a count variable to 0 and two pointers, middle_node, and current_node to the head of the linked list.
2.Traverse the linked list using current_node and increment the count variable by 1 in each iteration.
3.If the count variable is odd, move the middle_node pointer to the next node.
4.Return the data of the middle_node pointer as it points to the middle element.

Python3




class Node:
    def __init__(self, data):
        self.data = data
        self.next = None
 
class LinkedList:
    def __init__(self):
        self.head = None
         
    def insert(self, data):
        new_node = Node(data)
        if self.head is None:
            self.head = new_node
        else:
            current_node = self.head
            while current_node.next is not None:
                current_node = current_node.next
            current_node.next = new_node
             
    def print_list(self):
        current_node = self.head
        while current_node is not None:
            print(current_node.data, end="->")
            current_node = current_node.next
        print("NULL")
     
    def find_middle(self):
        elements = []
        current_node = self.head
        while current_node is not None:
            elements.append(current_node.data)
            current_node = current_node.next
        middle_index = len(elements) // 2
        return elements[middle_index]
         
linked_list = LinkedList()
linked_list.insert(1)
linked_list.insert(2)
linked_list.insert(3)
linked_list.insert(4)
linked_list.insert(5)
linked_list.print_list()
 
middle = linked_list.find_middle()
print("The middle element is:", middle)


Output

1->2->3->4->5->NULL
The middle element is: 3

Time complexity: O(n), where n is the number of nodes in the linked list. We traverse the linked list only once.

Space complexity: O(1). We use a constant amount of extra space to store pointers and variables.



Previous Article
Next Article

Similar Reads

Python Program For Finding The Middle Element Of A Given Linked List
Given a singly linked list, find the middle of the linked list. For example, if the given linked list is 1->2->3->4->5 then the output should be 3. If there are even nodes, then there would be two middle nodes, we need to print the second middle element. For example, if given linked list is 1->2->3->4->5->6 then the outpu
4 min read
Python program to get the indices of each element of one list in another list
Given 2 lists, get all the indices of all occurrence of each element in list2 from list1. Input : test_list = [4, 5, 3, 7, 8, 3, 2, 4, 3, 5, 8, 3], get_list = [7, 5, 4] Output : [[3], [1, 9], [0, 7]] Explanation : 5 is present at 1st and 9th index. Input : test_list = [4, 5, 3, 7, 8, 3, 2, 4, 3, 5, 8, 3], get_list = [7, 5, 8] Output : [[3], [1, 9],
7 min read
Python program to check if a string has at least one letter and one number
Given a string in Python. The task is to check whether the string has at least one letter(character) and one number. Return “True” if the given string fully fill the above condition else return “False” (without quotes). Examples: Input: welcome2ourcountry34 Output: True Input: stringwithoutnum Output: False Approach: The approach is simple we will
4 min read
Python3 Program to Move all zeroes to end of array | Set-2 (Using single traversal)
Given an array of n numbers. The problem is to move all the 0's to the end of the array while maintaining the order of the other elements. Only single traversal of the array is required.Examples:   Input : arr[] = {1, 2, 0, 0, 0, 3, 6} Output : 1 2 3 6 0 0 0 Input: arr[] = {0, 1, 9, 8, 4, 0, 0, 2, 7, 0, 6, 0, 9} Output: 1 9 8 4 2 7 6 9 0 0 0 0 0
2 min read
Python - Add Phrase in middle of String
Given a String, add a phrase in the middle of it. Input : test_str = 'geekforgeeks is for geeks', mid_str = "good" Output : geekforgeeks is good for geeks Explanation : Added just in middle, after 2 words. Input : test_str = 'geekforgeeks best', mid_str = "is" Output : geekforgeeks is best Explanation : Added just in middle, after 1 word. Method #1
7 min read
Python - K middle elements
Given a List, extract K elements occurring in middle of list. Input : test_list = [2, 3, 5, 7, 8, 5, 3, 5, 9], K = 3 Output : [7, 8, 5] Explanation : Middle 3 elements are extracted. Input : test_list = [2, 3, 5, 7, 8, 5, 3, 5, 9], K = 7 Output : [3, 5, 7, 8, 5, 3, 5] Explanation : Middle 7 elements are extracted. Method #1: Using loop In this, we
5 min read
Get Discrete Linear Convolution of 2D sequences and Return Middle Values in Python
In this article let's see how to return the discrete linear convolution of two one-dimensional sequences and return the middle values using NumPy in python. numpy.convolve method : The numpy.convolve() Converts two one-dimensional sequences into a discrete, linear convolution. In signal processing, the convolution operator is used to describe the e
4 min read
Python Program to Implement Stack Using Linked List
In Python, creating a stack using a linked list involves implementing a data structure where elements are added and removed in a last-in-first-out (LIFO) manner. This approach uses the concept of nodes interconnected by pointers, allowing efficient insertion and deletion operations. We are given a Linked list and our task is to create a stack using
4 min read
Python3 Program to Rotate the sub-list of a linked list from position M to N to the right by K places
Given a linked list and two positions 'm' and 'n'. The task is to rotate the sublist from position m to n, to the right by k places. Examples: Input: list = 1->2->3->4->5->6, m = 2, n = 5, k = 2 Output: 1->4->5->2->3->6 Rotate the sublist 2 3 4 5 towards right 2 times then the modified list are: 1 4 5 2 3 6 Input: list
4 min read
Python | Move one list element to another list
Sometimes, while working with Python list, there can be a problem in which we need to perform the inter list shifts of elements. Having a solution to this problem is always very useful. Let's discuss certain way in which this task can be performed. Method : Using pop() + insert() + index() This particular task can be performed using combination of
6 min read
Practice Tags :