Python Program To Check Whether The Length Of Given Linked List Is Even Or Odd
Last Updated :
15 Feb, 2023
Given a linked list, the task is to make a function which checks whether the length of the linked list is even or odd.
Examples:
Input : 1->2->3->4->NULL
Output : Even
Input : 1->2->3->4->5->NULL
Output : Odd
Method 1: Count the codes linearly
Traverse the entire Linked List and keep counting the number of nodes. As soon as the loop is finished, we can check if the count is even or odd. You may try it yourself.
Method 2: Stepping 2 nodes at a time
Approach:
1. Take a pointer and move that pointer two nodes at a time
2. At the end, if the pointer is NULL then length is Even, else Odd.
Python3
class Node:
def __init__( self , d):
self .data = d
self . next = None
self .head = None
def LinkedListLength( self ):
while ( self .head ! = None and
self .head. next ! = None ):
self .head = self .head. next . next
if ( self .head = = None ):
return 0
return 1
def push( self , info):
node = Node(info)
node. next = ( self .head)
( self .head) = node
head = Node( 0 )
head.push( 4 )
head.push( 5 )
head.push( 7 )
head.push( 2 )
head.push( 9 )
head.push( 6 )
head.push( 1 )
head.push( 2 )
head.push( 0 )
head.push( 5 )
head.push( 5 )
check = head.LinkedListLength()
if (check = = 0 ):
print ( "Even" )
else :
print ( "Odd" )
|
Time Complexity: O(n)
Space Complexity: O(1)
Method: Using recursion
Python3
class Node:
def __init__( self , d):
self .data = d
self . next = None
self .head = None
def LinkedListLength( self , current = None ):
if current is None :
return 0
return 1 + self .LinkedListLength(current. next )
def push( self , info):
node = Node(info)
node. next = ( self .head)
( self .head) = node
head = Node( 0 )
head.push( 4 )
head.push( 5 )
head.push( 7 )
head.push( 2 )
head.push( 9 )
head.push( 6 )
head.push( 1 )
head.push( 2 )
head.push( 0 )
head.push( 5 )
length = head.LinkedListLength()
if length % 2 = = 0 :
print ( "Even" )
else :
print ( "Odd" )
|
Time Complexity: O(n)
Auxiliary Space: O(n)
Please refer complete article on Check whether the length of given linked list is Even or Odd for more details!
Method: Using Two pointer approach:
Python3
class Node:
def __init__( self , data):
self .data = data
self . next = None
class LinkedList:
def __init__( self ):
self .head = None
def length( self ):
slow_ptr = self .head
fast_ptr = self .head
while fast_ptr is not None and fast_ptr. next is not None :
slow_ptr = slow_ptr. next
fast_ptr = fast_ptr. next . next
if fast_ptr is None :
return "Even"
else :
return "Odd"
linked_list = LinkedList()
linked_list.head = Node( 1 )
linked_list.head. next = Node( 2 )
linked_list.head. next . next = Node( 3 )
linked_list.head. next . next . next = Node( 4 )
length = linked_list.length()
print ( "Length:" , length)
|
Time Complexity: O(n)
Auxiliary Space: O(n)
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...