patternjavaMinor
Determining if the length of LinkedList is even or odd
Viewed 0 times
determiningthelinkedlistlengthevenodd
Problem
Today, I tackled this coding question:
Given a singly-linked list, check whether its length is even or odd in a single pass. An Empty list has 0 nodes which makes the number of nodes in it even.
Would the time complexity of my code be O(n)? Do you guys see any improvements that can be made?
Given a singly-linked list, check whether its length is even or odd in a single pass. An Empty list has 0 nodes which makes the number of nodes in it even.
Would the time complexity of my code be O(n)? Do you guys see any improvements that can be made?
public Boolean isListEven(ListNode head) {
if(head == null){
return true;
}
if(head.next.next == null){
return false;
}
int count = 1;
while(head.next != null){
if(head.next.next != null){
count = count + 2;
head = head.next.next;
}
count = count + 1;
head = head.next;
}
return (count % 2 == 0);
}Solution
The method signature is a bit odd, returning a
If the list has one node, then your code will crash on
You don't need to keep track of
The trick is to observe the loop invariant: each iteration through the loop, it advances
Boolean object instead of a primitive boolean. A clearer name would be isListLengthEven(). The function could be static, since it does not rely on any object state.If the list has one node, then your code will crash on
if(head.next.next == null). In general, you should avoid cluttering your code with unnecessary special cases.You don't need to keep track of
count. This solution, like yours, is O(n), but it is much simpler:public static boolean isListLengthEven(ListNode head) {
for (; head != null; head = head.next.next) {
if (head.next == null) return false;
}
return true;
}The trick is to observe the loop invariant: each iteration through the loop, it advances
head by two nodes, so that the picture at the top of the loop is always equivalent to the original. If it can't advance by two, then the list has an odd length.Code Snippets
public static boolean isListLengthEven(ListNode head) {
for (; head != null; head = head.next.next) {
if (head.next == null) return false;
}
return true;
}Context
StackExchange Code Review Q#158364, answer score: 6
Revisions (0)
No revisions yet.