The question is to find if the given linked list length is even or odd in optimum time. We will use a fast pointer, i.e 2x pointer. the fast pointer moves two nodes at a time. In the end, we will either be having the node as Null or the Node will be the last node in the Linked list. if the node is Null means the length of the list is Even otherwise Odd.
Java code for the above problem is :
package askgif.linkedlist;
import java.util.Stack;
class ListNode{
public int data;
public ListNode next;
ListNode(int data){
this.data = data;
}
};
public class LinkedListNode {
public static void main(String[] args) {
ListNode node1 = new ListNode(1);
ListNode node2 = new ListNode(2);
ListNode node3 = new ListNode(3);
ListNode node4 = new ListNode(4);
ListNode node5 = new ListNode(5);
ListNode node6 = new ListNode(6);
ListNode node7 = new ListNode(7);
ListNode node8 = new ListNode(8);
ListNode node9 = new ListNode(9);
ListNode node10 = new ListNode(10);
ListNode node11 = new ListNode(11);
node1.next = node2;
node2.next = node3;
node3.next = node4;
node4.next = node5;
node5.next = node6;
node6.next = node7;
node7.next = node8;
node8.next = node9;
node9.next = node10;
node10.next = node11;
node11.next = null;
System.out.println(IfLinkedListIsEven(node1));
}
private static Boolean IfLinkedListIsEven(ListNode node1) {
if(node1 == null)
return true;
while(node1 != null && node1.next != null)
node1 = node1.next.next;
return node1 == null;
}
}
output:
false
Time Complexity: O(n)
Space Complexity: O(1)



