Given a linked list, task is to make a function which check whether the length of linked list is even or odd.
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
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.
Time Complexity: O(n)
Space Complexity: O(1)
This article is contributed by Sahil Rajput. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
- Length of longest palindrome list in a linked list using O(1) extra space
- Check if a linked list is Circular Linked List
- Run Length Decoding in Linked List
- Find length of loop in a Linked List using Map
- Find length of loop in linked list
- Find Length of a Linked List (Iterative and Recursive)
- Check if a Linked List is Pairwise Sorted
- Check linked list with a loop is palindrome or not
- Check if a doubly linked list of characters is palindrome or not
- Check if a linked list of strings forms a palindrome
- Check if elements of Linked List are present in pair
- Function to check if a singly linked list is palindrome
- Check if linked list is sorted (Iterative and Recursive)
- Check if a pair with given product exists in Linked list
- Check if absolute difference of consecutive nodes is 1 in Linked List
- Create new linked list from two given linked list with greater element at each node
- XOR Linked List – A Memory Efficient Doubly Linked List | Set 2
- Difference between Singly linked list and Doubly linked list
- Convert singly linked list into circular linked list
- XOR Linked List - A Memory Efficient Doubly Linked List | Set 1