C Program To Check Whether The Length Of Given Linked List Is Even Or Odd
Last Updated :
24 Jan, 2023
Given a linked list, the task is to make a function which checks whether the length of the linked list is even or odd.
Examples:
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
Approach:
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.
C
#include<stdio.h>
#include<stdlib.h>
struct Node
{
int data;
struct Node* next;
};
int LinkedListLength( struct Node* head)
{
while (head && head->next)
{
head = head->next->next;
}
if (!head)
return 0;
return 1;
}
void push( struct Node** head,
int info)
{
struct Node* node =
( struct Node*) malloc ( sizeof ( struct Node));
node->data = info;
node->next = (*head);
(*head) = node;
}
int main( void )
{
struct Node* head = NULL;
push(&head, 4);
push(&head, 5);
push(&head, 7);
push(&head, 2);
push(&head, 9);
push(&head, 6);
push(&head, 1);
push(&head, 2);
push(&head, 0);
push(&head, 5);
push(&head, 5);
int check =
LinkedListLength(head);
if (check == 0)
{
printf ( "Even" );
}
else
{
printf ( "Odd" );
}
return 0;
}
|
Output:
Odd
Time Complexity: O(n)
Auxiliary Space: O(1)
Using Recursion
C
#include<stdio.h>
#include<stdlib.h>
struct Node
{
int data;
struct Node* next;
};
int LinkedListLength( struct Node* head)
{
if (head == NULL) return 0;
return 1+LinkedListLength(head->next);
}
void push( struct Node** head,
int info)
{
struct Node* node =
( struct Node*) malloc ( sizeof ( struct Node));
node->data = info;
node->next = (*head);
(*head) = node;
}
int main( void )
{
struct Node* head = NULL;
push(&head, 4);
push(&head, 5);
push(&head, 7);
push(&head, 2);
push(&head, 9);
push(&head, 6);
push(&head, 1);
push(&head, 2);
push(&head, 0);
push(&head, 5);
push(&head, 5);
int check =
LinkedListLength(head);
if (check == 0)
{
printf ( "Even" );
}
else
{
printf ( "Odd" );
}
return 0;
}
|
Time Complexity: O(n)
Auxiliary Space: O(n)
Please refer complete article on Check whether the length of given linked list is Even or Odd for more details!
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...