Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Python Tutorial
  • Interview Questions
  • Python Quiz
  • Python Glossary
  • Python Projects
  • Practice Python
  • Data Science With Python
  • Python Web Dev
  • DSA with Python
  • Python OOPs
Open In App
Next Article:
Python Program For Inserting Node In The Middle Of The Linked List
Next article icon

Python Program To Check Whether The Length Of Given Linked List Is Even Or Odd

Last Updated : 15 Feb, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

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
Recommended: Please solve it on "PRACTICE" first, before moving on to the solution.

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)

Method: Using recursion

Python3
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, current=None):          # if current is None:              #current = self.head          if current is None:              return 0          return 1 + self.LinkedListLength(current.next)      # 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)   length = head.LinkedListLength()   # Checking for length of  # linklist  if length % 2 == 0:      print("Even")  else:      print("Odd")  # This code is contributed by Vinay Pinjala. 

Output
Even

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
# Define the Node class to create nodes for the linked list class Node:     def __init__(self, data):         self.data = data         self.next = None # Define the LinkedList class to create and manage linked lists class LinkedList:     def __init__(self):         self.head = None     # Function to determine the length of the linked list     def length(self):         slow_ptr = self.head # Initialize the slow pointer to the head of the list         fast_ptr = self.head # Initialize the fast pointer to the head of the list         # Move the slow pointer one step at a time         # Move the fast pointer two steps at a time         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 the fast pointer reaches the end of the list, the length is even         if fast_ptr is None:             return "Even"         # If the fast pointer reaches the last node of the list, the length is odd         else:             return "Odd" # Initialize a linked list and add some nodes to it 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) # Determine the length of the linked list length = linked_list.length() print("Length:", length) #This code is contributed by Jyothi pinjala. 

Output
Length: Even

Time Complexity: O(n)
Auxiliary Space: O(n)


Next Article
Python Program For Inserting Node In The Middle Of The Linked List
author
kartik
Improve
Article Tags :
  • Linked List
  • Python Programs
  • DSA
Practice Tags :
  • Linked List

Similar Reads

  • Python Program For Inserting Node In The Middle Of The Linked List
    Given a linked list containing n nodes. The problem is to insert a new node with data x at the middle of the list. If n is even, then insert the new node after the (n/2)th node, else insert the new node after the (n+1)/2th node. Examples: Input : list: 1->2->4->5 x = 3 Output : 1->2->
    4 min read
  • Python Program For Finding The Length Of Loop In Linked List
    Write a function detectAndCountLoop() that checks whether a given Linked List contains loop and if loop is present then returns count of nodes in loop. For example, the loop is present in below-linked list and length of the loop is 4. If the loop is not present, then the function should return 0. Re
    4 min read
  • Python Program to Check if a Number is Odd or Even
    Even Numbers are exactly divisible by 2 and Odd Numbers are not exactly divisible by 2. We can use modulo operator (%) to check if the number is even or odd. For even numbers, the remainder when divided by 2 is 0, and for odd numbers, the remainder is 1. In this article, we will learn how to check i
    2 min read
  • Python Program For Finding Length Of A Linked List
    Write a function to count the number of nodes in a given singly linked list. For example, the function should return 5 for linked list 1->3->1->2->1. Recommended: Please solve it on "PRACTICE" first, before moving on to the solution. Iterative Solution: 1) Initialize count as 0 2) Initia
    6 min read
  • Python Program For Finding The Middle Element Of A Given Linked List
    Given a singly linked list, find the middle of the linked list. For example, if the given linked list is 1->2->3->4->5 then the output should be 3. If there are even nodes, then there would be two middle nodes, we need to print the second middle element. For example, if given linked list
    4 min read
  • Python program to find the sum of all even and odd digits of an integer list
    The following article shows how given an integer list, we can produce the sum of all its odd and even digits. Input : test_list = [345, 893, 1948, 34, 2346] Output : Odd digit sum : 36 Even digit sum : 40 Explanation : 3 + 5 + 9 + 3 + 1 + 9 + 3 + 3 = 36, odd summation.Input : test_list = [345, 893]
    5 min read
  • Python Program to test whether the length of rows are in increasing order
    Given a Matrix, the following program is used to test if length all rows of a matrix are in increasing order or not. If yes, it returns True, otherwise False. Input : test_list = [[3], [1, 7], [10, 2, 4], [8, 6, 5, 1, 4]] Output : True Explanation : 1 < 2 < 3 < 5, increasing lengths of rows
    4 min read
  • Python Program To Delete Middle Of Linked List
    Given a singly linked list, delete the middle of the linked list. For example, if the given linked list is 1->2->3->4->5 then the linked list should be modified to 1->2->4->5 If there are even nodes, then there would be two middle nodes, we need to delete the second middle element. For example, if g
    4 min read
  • Python Program for Check if count of divisors is even or odd
    Write a Python program for a given number “n”, the task is to find its total number of divisors that are even or odd. Examples: Input : n = 10 Output: Even Input: n = 100Output: Odd Input: n = 125Output: Even Python Program for Check if count of divisors is even or odd using Naive Approach:A naive a
    4 min read
  • Python Program To Delete Alternate Nodes Of A Linked List
    Given a Singly Linked List, starting from the second node delete all alternate nodes of it. For example, if the given linked list is 1->2->3->4->5 then your function should convert it to 1->3->5, and if the given linked list is 1->2->3->4 then convert it to 1->3. Recomm
    3 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences