Python Program To Check Whether The Length Of Given Linked List Is Even Or Odd
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
# Python program to check length # of a given linklist # Defining structure class Node: def __init__( self , d): self .data = d self . next = None self .head = None # Function to check the length # of linklist 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 # Push function def push( self , info): # Allocating node node = Node(info) # Next of new node to head node. next = ( self .head) # head points to new node ( self .head) = node # Driver code head = Node( 0 ) # Adding elements to Linked List 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() # Checking for length of # linklist if (check = = 0 ): print ( "Even" ) else : print ( "Odd" ) # This code is contributed by Prerna saini |
Output:
Odd
Time Complexity: O(n)
Space Complexity: O(1)
Please refer complete article on Check whether the length of given linked list is Even or Odd for more details!