Python Program to Print Middle most Node of a Linked List

PythonServer Side ProgrammingProgramming

When it is required to print the middle most element of a linked list, a method named ‘print_middle_val’ is defined. This method takes the linked list as a parameter and gets the middle most element.

Below is a demonstration for the same −

Example

 Live Demo

class Node:
   def __init__(self, data):
      self.data = data
      self.next = None

class LinkedList_structure:
   def __init__(self):
      self.head = None
      self.last_node = None

   def add_vals(self, data):
      if self.last_node is None:
         self.head = Node(data)
         self.last_node = self.head
      else:
         self.last_node.next = Node(data)
         self.last_node = self.last_node.next

def print_middle_val(my_list):
   curr = my_list.head
   my_len = 0
   while curr:
      curr = curr.next
      my_len = my_len + 1

   curr = my_list.head
   for i in range((my_len - 1)//2):
      curr = curr.next

   if curr:
      if my_len % 2 == 0:
         print('The two middle elements are {} and {}'.format(curr.data, curr.next.data))
      else:
         print('The middle-most element is {}.'.format(curr.data))
   else:
      print('The list is empty')

my_instance = LinkedList_structure()

my_list = input('Enter the elements of the linked list... ').split()
for elem in my_list:
   my_instance.add_vals(int(elem))

print_middle_val(my_instance)

Output

Enter the elements of the linked list... 56 23 78 99 34 11
The two middle elements are 78 and 99

Explanation

  • The ‘Node’ class is created.

  • Another ‘LinkedList_structure’ class with required attributes is created.

  • It has an ‘init’ function that is used to initialize the first element, i.e the ‘head’ to ‘None’.

  • A method named ‘add_vals’ is defined, that helps add a value to the stack.

  • Another method named ‘print_middle_val’ is defined, that helps display the middle value of the linked list on the console.

  • An instance of the ‘LinkedList_structure’ is created.

  • Elements are added to the linked list.

  • The elements are displayed on the console.

  • The ‘print_middle_val’ method is called on this linked list.

  • The output is displayed on the console.

raja
Published on 14-Apr-2021 17:37:08
Advertisements