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.
<script> // JavaScript program to check length // of a given linklist // Defining structure class Node { constructor()
{
this .data = 0;
this .next = null ;
}
} // Function to check the length of // linklist function LinkedListLength(head)
{ while (head != null &&
head.next != null )
{
head = head.next.next;
}
if (head == null )
return 0;
return 1;
} // Push function function push(head, info)
{ // Allocating node
node = new Node();
// Info into node
node.data = info;
// Next of new node to head
node.next = (head);
// head points to new node
(head) = node;
} // Driver code head = null ;
// Adding elements to Linked List 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); var check = LinkedListLength(head);
// Checking for length of linklist if (check == 0)
{ document.write( "Odd" );
} else { document.write( "Even" );
} // This code is contributed by umadevi9616 </script> |
Output:
Odd
Time Complexity: O(n)
Auxiliary Space: O(1)
Using Recursion
<script> // JavaScript program to check length // of a given linklist // Defining structure class Node { constructor()
{
this .data = 0;
this .next = null ;
}
} // Recursive Function to check the length of // linklist function LinkedListLengthRecursive(head) {
if (head == null ) {
return 0;
}
return 1 + LinkedListLengthRecursive(head.next);
} // Push function function push(head, info)
{ // Allocating node
node = new Node();
// Info into node
node.data = info;
// Next of new node to head
node.next = (head);
// head points to new node
(head) = node;
} // Driver code head = null ;
// Adding elements to Linked List 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); var check = LinkedListLengthRecursive(head);
// Checking for length of linklist if (check == 0)
{ console.log( "Odd" );
} else { console.log( "Even" );
} // This code is contributed by Vinay Pinjala. </script> |
Odd
Time Complexity: O(n)
Auxiliary Space: O(1)
Please refer complete article on Check whether the length of given linked list is Even or Odd for more details!