Skip to main content

Linked List Length Even or Odd

Problem​

Given a linked list of size n, your task is to complete the function isLengthEvenOrOdd() which contains the head of the linked list and check whether the length of the linked list is even or odd.

Examples:​

Example 1:

Input:
n = 3
linked list = 9->4->3
Output:
Odd
Explanation:
The length of linked list is 3 which is odd.

Example 2:

Input:
n = 6
linked list = 12->52->10->47->95->0
Output:
Even
Explanation:
The length of linked list is 6 which is even.

Your task:​

Since this is a functional problem you don't have to worry about input, you just have to complete the function isLengthEvenOrOdd() which takes the head of the linked list as the input parameter and returns 0 if the length of the linked list is even otherwise returns 1.

  • Expected Time Complexity: O(n)O(n)
  • Expected Auxiliary Space: O(1)O(1)

Constraints:​

  • 1<=n<=1041 <= n <= 10^4
  • 1<=1 <= elements of the linked list <=103<= 10^3

Solution​

Python​

def isLengthEvenOrOdd(head):
count = 0
temp = head
while temp is not None:
count+=1
temp = temp.next
if count%2==0:
return 0
else:
return 1

Java​

public int isLengthEvenOrOdd(Node head) {
int count = 0;
Node temp = head;
while(temp!=null) {
count+=1;
temp = temp.next;
}
if(count%2==0)
return 0;
else
return 1;
}

C++​

int isLengthEvenOrOdd(struct Node* head) {
int count = 0;
Node* temp = head;
while(temp!=nullptr) {
count+=1;
temp = temp->next;
}
if(count%2==0)
return 0;
else
return 1;
}

C​

int isLengthEvenOrOdd(struct Node* head) {
int count = 0;
struct Node* temp = head;
while (temp != NULL) {
count += 1;
temp = temp->next;
}
if (count % 2 == 0)
return 0;
else
return 1;
}
  • Time Complexity: O(n)O(n)
  • Auxiliary Space: O(1)O(1)