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

PythonServer Side ProgrammingProgramming

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
      self.next = next

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

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

Input

[5,8,7,4,3,6,4,5,8]

Output

Odd
raja
Published on 16-Jan-2021 09:27:08
Advertisements