Check whether the given Linked List length is even or odd?
💻 coding

Check whether the given Linked List length is even or odd?

1 min read 237 words
1 min read
ShareWhatsAppPost on X
  • 1To determine if a linked list's length is even or odd, a fast pointer moves two nodes at a time.
  • 2If the fast pointer ends on a null node, the length is even; otherwise, it is odd.
  • 3The algorithm has a time complexity of O(n) and a space complexity of O(1).

AI-generated summary · May not capture all nuances

Key Insight
AskGif

"To determine if a linked list's length is even or odd, a fast pointer moves two nodes at a time."

Check whether the given Linked List length is even or odd?

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)

Enjoyed this article?

Share it with someone who'd find it useful.

ShareWhatsAppPost on X

AskGif

Published on 7 August 2018 · 1 min read · 237 words

Part of AskGif Blog · coding

You might also like

Check whether the given Linked List length is even or odd? | AskGif Blog