700573. Is Linked List Length Even?
Basic
Is Linked List Length Even?
Slug: linked-list-length-even-or-odd
Difficulty: Basic
Topic Tags: Linked List, Data Structures
Company Tags: None
Summary
Given a singly-linked list, determine whether its length is even or odd. This problem involves basic concepts of linked lists and algorithmic thinking.
Detailed Explanation
To solve this problem, we can use a simple iterative approach to traverse the linked list and count the number of nodes. Since we're interested in determining whether the length is even or odd, we don't need to worry about the actual value of the length; just its parity (even or odd) is sufficient.
Here's a step-by-step breakdown of the solution:
- Initialize a variable
countto 0. - Traverse the linked list until the end is reached:
- For each node, increment
countby 1.
- For each node, increment
- Check whether
countis even (i.e., divisible by 2) or odd.
Time complexity: O(n), where n is the length of the linked list. Space complexity: O(1), as we only use a single variable to store the count.
Optimized Solutions
Java
public boolean isLinkedListLengthEven(ListNode head) {
int count = 0;
ListNode current = head;
while (current != null) {
count++;
current = current.next;
}
return count % 2 == 0;
}