Is Linked List Length Even
JavaView on GFG
Time: O(n)
Space: O(1)
Problem Overview
Check if linked list has even length.
See our study guide for structured GFG and LeetCode practice.
Intuition
Check if linked list has even length. Count nodes or advance two pointers.
Algorithm
- 1Fast pointer: advance by 2 each step. If fast reaches null: even. If fast.next reaches null: odd.
Common Pitfalls
- • O(n/2) with fast pointer. Or simply count and check % 2.
Is Linked List Length Even.java
Java
// Approach: Move pointer two steps at a time; if null, length is even; if null after one step, odd.
// Time: O(n) Space: O(1)
class Solution {
public boolean isLengthEven(Node head) {
Node curr = head;
int len = 0;
while (curr != null) {
curr = curr.next;
len++;
}
return len % 2 == 0;
}
}Was this solution helpful?