Check whether the length of given linked list is Even or Odd in Python

Suppose we have a linked list, we have to check whether the length of it is odd or even.

So, if the input is like head = [5,8,7,4,3,6,4,5,8], then the output will be Odd.

To solve this, we will follow these steps −

  • while head is not null and next of head is not null, do
    • head := next of next of head
  • if head is null, then
    • return "Even"
  • return "Odd"

Let us see the following implementation to get better understanding −

Example Code

Live Demo

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

def make_list(elements):
   head = ListNode(elements[0])
   for element in elements[1:]:
      ptr = head
         ptr = = ListNode(element)
   return head
def solve(head):
   while head != None and != None: 
      head =
   if head == None:
      return "Even"
   return "Odd"

head = make_list([5,8,7,4,3,6,4,5,8])