The Wayback Machine - https://web.archive.org/web/20240926155247/https://www.geeksforgeeks.org/find-length-of-loop-in-linked-list/
Open In App

Find length of loop/cycle in given Linked List

Last Updated : 13 Sep, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow
Solve Problem
Easy
44.26%
2L

Given the head of a linked list. The task is to find the length of the loop in the linked list. If the loop is not present return 0.

Examples:

Input: head: 25 -> 14 -> 19 -> 33 -> 10 -> 21 -> 39 ->90 ->58 -> 45 -> 33
Output: 7
Explanation: The loop is present in the below-linked list and the length of the loop is 7. 


Input: head: 4 -> 3 -> 7 -> 9 -> 2
Output: 0
Explanation: There is no loop present in the Linked List.

[Naive Approach] Using HashSet – O(n) Time and O(n) Space:

The idea is to maintain use Hashset to keep track of visited nodes so far. if the node is not present in Hashset we will insert and move to another node , else we will maintain a counter from that node and will start traversing until we reach to it again by incrementing the counter variable every time.

Below is the implementation of the above approach:

C++
// C++ program to count number of nodes
// in loop in a linked list if loop is present

#include <bits/stdc++.h>
using namespace std;

class Node {
public:
    int data;
    Node* next;
    Node(int x) {
         data = x;
          next = nullptr;
    }
};

// This function detects and counts loop
// nodes in the list. If loop is not there
// then returns 0
int countNodesinLoop(Node* head) {
  
    unordered_set<Node*> visited;
    Node* current = head;
    int count = 0;

    while (current != nullptr) {
      
        // If the node is already visited, 
          // it means there is a loop
        if (visited.find(current) != visited.end()) {
            struct Node* startOfLoop = current;
            do {
                count++;
                current = current->next;
            } while (current != startOfLoop);
            return count;
        }

        // Mark the current node as visited
        visited.insert(current);

        // Move to the next node
        current = current->next;
    }

    // Return 0 to indicate that
    //   there is no loop
    return 0;
}

int main() {
      
      //create linked list 1->2->3->4->5
    Node* head = new Node(1);
    head->next = new Node(2);
    head->next->next = new Node(3);
    head->next->next->next = new Node(4);
    head->next->next->next->next = new Node(5);
      
      //loop from 5 to 2
    head->next->next->next->next->next = head->next;

    cout << countNodesinLoop(head) << endl;

    return 0;
}
Java
// Java program to count number of nodes
// in loop in a linked list if loop is present

import java.util.HashSet;

class Node {
    int data;
    Node next;

    Node(int data) {
        this.data = data;
        this.next = null;
    }
}

public class GfG {
  
    // Function to detect and count loop nodes in the list
    static int countNodesInLoop(Node head) {
        HashSet<Node> visited = new HashSet<>();
        Node current = head;
        int count = 0;

        while (current != null) {
          
            // If the node is already visited, it means
            // there is a loop
            if (visited.contains(current)) {
                Node startOfLoop = current;
                do {
                    count++;
                    current = current.next;
                } while (current != startOfLoop);
                return count;
            }

            // Mark the current node as visited
            visited.add(current);

            // Move to the next node
            current = current.next;
        }

        // Return 0 to indicate that there is no loop
        return 0;
    }

    public static void main(String[] args) {
      
          //create linked list 1->2->3->4->5
        Node head = new Node(1);
        head.next = new Node(2);
        head.next.next = new Node(3);
        head.next.next.next = new Node(4);
        head.next.next.next.next = new Node(5);
      
        //loop from 5 to 2
        head.next.next.next.next.next = head.next;

        System.out.println(countNodesInLoop(head));
    }
}
Python
# Python program to count number of nodes
# in loop in a linked list if loop is present

class Node:
    def __init__(self, x):
        self.data = x
        self.next = None

def count_nodes_in_loop(head):
    visited = set()
    current = head
    count = 0

    while current:
      
        # If the node is already visited, 
        # it means there is a loop
        if current in visited:
            start_of_loop = current
            while True:
                count += 1
                current = current.next
                if current == start_of_loop:
                    break
            return count
        
        # Mark the current node as visited
        visited.add(current)

        # Move to the next node
        current = current.next

    # Return 0 to indicate that there is no loop
    return 0

#create linked list 1->2->3->4->5
head = Node(1)
head.next = Node(2)
head.next.next = Node(3)
head.next.next.next = Node(4)
head.next.next.next.next = Node(5)

#loop from 5 to 2
head.next.next.next.next.next = head.next

print(count_nodes_in_loop(head))
C#
// C# program to count number of nodes
// in loop in a linked list if loop is present

using System;
using System.Collections.Generic;

class Node {
    public int Data;
    public Node Next;

    public Node(int data) {
        Data = data;
        Next = null;
    }
}

class GfG {
  
    // Function to detect and count 
      // loop nodes in the list
    static int CountNodesInLoop(Node head) {
        HashSet<Node> visited = new HashSet<Node>();
        Node current = head;
        int count = 0;

        while (current != null) {
          
            // If the node is already visited, 
              // it means there is a loop
            if (visited.Contains(current)) {
                Node startOfLoop = current;
                do {
                    count++;
                    current = current.Next;
                } while (current != startOfLoop);
                return count;
            }

            // Mark the current node as visited
            visited.Add(current);

            // Move to the next node
            current = current.Next;
        }

        // Return 0 to indicate that there is no loop
        return 0;
    }

    static void Main() {
      
          //create linked list 1->2->3->4->5
        Node head = new Node(1);
        head.Next = new Node(2);
        head.Next.Next = new Node(3);
        head.Next.Next.Next = new Node(4);
        head.Next.Next.Next.Next = new Node(5);

        // loop from 5 to 2
        head.Next.Next.Next.Next.Next = head.Next;

        Console.WriteLine(CountNodesInLoop(head));
    }
}
JavaScript
// Javascript program to count number of nodes
// in loop in a linked list if loop is present

class Node {
    constructor(x) {
        this.data = x;
        this.next = null;
    }
}

function countNodesInLoop(head) {
    const visited = new Set();
    let current = head;
    let count = 0;

    while (current) {
    
        // If the node is already visited, 
        // it means there is a loop
        if (visited.has(current)) {
            const startOfLoop = current;
            do {
                count++;
                current = current.next;
            } while (current !== startOfLoop);
            return count;
        }

        // Mark the current node as visited
        visited.add(current);

        // Move to the next node
        current = current.next;
    }

    // Return 0 to indicate that 
    // there is no loop
    return 0;
}

//create linked list 1->2->3->4->5
const head = new Node(1);
head.next = new Node(2);
head.next.next = new Node(3);
head.next.next.next = new Node(4);
head.next.next.next.next = new Node(5);

//loop from 5 to 2
head.next.next.next.next.next = head.next;

console.log(countNodesInLoop(head));

Output
4

Time complexity: O(n), where n is the number of nodes in the linked list.
Auxiliary Space: O(n).

[Expected Approach] : Using Floyd’s Cycle detection algorithm – O(n) Time and O(1) Space:

The idea is to use Floyd’s Cycle detection algorithm for detecting the common point in the loop.

  • if common point exists , increment a count variable by 1 and start traversing from that point until we reach to the node again. Return count as length of loop.
  • else return 0 , because there is no loop in linked list.

Below is the implementation of the above approach:

C++
// C++ program to count number of nodes
// in loop in a linked list if loop is present

#include <bits/stdc++.h>
using namespace std;

class Node {
public:
    int data;
    Node* next;
      Node(int x) {
         data = x;
          next = nullptr;
    }
};

// Returns count of nodes present in loop.
int countNodes(Node* node) {
    int res = 1;
    Node* curr = node;
    while (curr->next != node) {
        res++;
        curr = curr->next;
    }
    return res;
}

// This function detects and counts loop
//  nodes in the list. If loop is not there
//  then returns 0 
int countNodesinLoop(Node* head) {
    Node *slow = head, *fast = head;

    while (slow != nullptr && fast != nullptr 
           && fast->next != nullptr) {
        slow = slow->next;
        fast = fast->next->next;

        // If slow and fast meet at
        // some point then there is a loop
        if (slow == fast)
            return countNodes(slow);
    }

    // Return 0 to indicate that
    //   there is no loop
    return 0;
}

int main() {
  
      // Create the linked list: 1->2->3->4->5
    Node* head = new Node(1);
    head->next = new Node(2);
    head->next->next = new Node(3);
    head->next->next->next = new Node(4);
    head->next->next->next->next = new Node(5);

    //loop from 5 to 2
    head->next->next->next->next->next = head->next;
    cout << countNodesinLoop(head) << endl;

    return 0;
}
C
// C program to count number of nodes
// in loop in a linked list if loop is present

#include <stdio.h>
#include <stdlib.h>

struct Node {
    int data;
    struct Node* next;
};

// Function to count the number of nodes in the loop
int countNodes(struct Node* node) {
    int count = 1;
    struct Node* curr = node;
    while (curr->next != node) {
        count++;
        curr = curr->next;
    }
    return count;
}

// Function to detect and count nodes in the loop
// If there is no loop, it returns 0
int countNodesInLoop(struct Node* head) {
    struct Node *slow = head, *fast = head;

    while (slow != NULL && fast != NULL && fast->next != NULL) {
        slow = slow->next;
        fast = fast->next->next;

        // If slow and fast meet at some 
          // point then there is a loop
        if (slow == fast)
            return countNodes(slow);
    }

    // Return 0 to indicate that there is no loop
    return 0;
}

struct Node* createNode(int data) {
    struct Node* newNode = 
      (struct Node*)malloc(sizeof(struct Node));
    newNode->data = data;
    newNode->next = NULL;
    return newNode;
}

int main() {
  
    // Create the linked list: 1->2->3->4->5
    struct Node* head = createNode(1);
    head->next = createNode(2);
    head->next->next = createNode(3);
    head->next->next->next = createNode(4);
    head->next->next->next->next = createNode(5);

    // loop from 5 to 2
    head->next->next->next->next->next = head->next;
    printf("%d\n", countNodesInLoop(head));

    return 0;
}
Java
// Java program to count number of nodes
// in loop in a linked list if loop is present
class Node {
    int data;
    Node next;

    Node(int x) {
        data = x;
        next = null;
    }
}

public class GfG {

    // Returns count of nodes present in loop.
    static int countNodes(Node node) {
        int count = 1;
        Node curr = node;
        while (curr.next != node) {
            count++;
            curr = curr.next;
        }
        return count;
    }

    // This function detects and counts loop nodes in the 
      // list. If loop is not there then returns 0
    static int countNodesInLoop(Node head) {
        Node slow = head;
        Node fast = head;

        while (slow != null && fast != null && fast.next != null) {
            slow = slow.next;
            fast = fast.next.next;

            // If slow and fast meet at some 
              // point then there is a loop
            if (slow == fast) {
                return countNodes(slow);
            }
        }

        // Return 0 to indicate that there is no loop
        return 0;
    }

    public static void main(String[] args) {
      
        // Create the linked list: 1->2->3->4->5
        Node head = new Node(1);
        head.next = new Node(2);
        head.next.next = new Node(3);
        head.next.next.next = new Node(4);
        head.next.next.next.next = new Node(5);

        // loop from 5 to 2
        head.next.next.next.next.next = head.next;
        System.out.println(countNodesInLoop(head));
    }
}
Python
# Python 3 program to find the number
# of nodes in loop in a linked list
# if loop is present

class Node:
    def __init__(self, x):
        self.data = x
        self.next = None

def count_nodes(node):
  
    # Returns count of nodes present in loop.
    count = 1
    curr = node
    while curr.next != node:
        count += 1
        curr = curr.next
    return count

def count_nodes_in_loop(head):
  
    # This function detects and counts 
    # loop nodes in the list. If loop is 
    # not there then returns 0
    slow = head
    fast = head

    while slow and fast and fast.next:
        slow = slow.next
        fast = fast.next.next

        # If slow and fast meet at some 
        # point then there is a loop
        if slow == fast:
            return count_nodes(slow)

    # Return 0 to indicate that there is no loop
    return 0

if __name__ == "__main__":
  
    # Create the linked list: 1->2->3->4->5
    head = Node(1)
    head.next = Node(2)
    head.next.next = Node(3)
    head.next.next.next = Node(4)
    head.next.next.next.next = Node(5)

    # loop from 5 to 2
    head.next.next.next.next.next = head.next
    print(count_nodes_in_loop(head))
C#
// C# program to count number of nodes
// in loop in a linked list if loop is present
using System;

class Node {
    public int Data;
    public Node Next;

    public Node(int x) {
        Data = x;
        Next = null;
    }
}

class GfG {
 
    // Returns count of nodes present in loop.
    static int CountNodes(Node node) {
        int count = 1;
        Node curr = node;
        while (curr.Next != node) {
            count++;
            curr = curr.Next;
        }
        return count;
    }

    // This function detects and counts loop nodes in 
      // the list. If loop is not there then returns 0
    static int CountNodesInLoop(Node head) {
        Node slow = head;
        Node fast = head;

        while (slow != null && fast != null && fast.Next != null) {
            slow = slow.Next;
            fast = fast.Next.Next;

            // If slow and fast meet at some 
              // point then there is a loop
            if (slow == fast) {
                return CountNodes(slow);
            }
        }

        // Return 0 to indicate that there is no loop
        return 0;
    }

    static void Main() {
      
        // Create the linked list: 1->2->3->4->5
        Node head = new Node(1);
        head.Next = new Node(2);
        head.Next.Next = new Node(3);
        head.Next.Next.Next = new Node(4);
        head.Next.Next.Next.Next = new Node(5);

        // loop from 5 to 2
        head.Next.Next.Next.Next.Next = head.Next;

        Console.WriteLine(CountNodesInLoop(head));
    }
}
JavaScript
// Javascript program to count number of nodes
// in loop in a linked list if loop is present

class Node {
    constructor(x) {
        this.data = x;
        this.next = null;
    }
}

// Returns count of nodes present in loop.
function countNodes(node) {
    let count = 1;
    let curr = node;
    while (curr.next !== node) {
        count++;
        curr = curr.next;
    }
    return count;
}

// This function detects and counts loop nodes in 
// the list. If loop is not there then returns 0
function countNodesInLoop(head) {
    let slow = head;
    let fast = head;

    while (slow && fast && fast.next) {
        slow = slow.next;
        fast = fast.next.next;

        // If slow and fast meet at some 
        // point then there is a loop
        if (slow === fast) {
            return countNodes(slow);
        }
    }

    // Return 0 to indicate that there is no loop
    return 0;
}

// Create the linked list: 1->2->3->4->5
const head = new Node(1);
head.next = new Node(2);
head.next.next = new Node(3);
head.next.next.next = new Node(4);
head.next.next.next.next = new Node(5);

// loop from 5 to 2
head.next.next.next.next.next = head.next;

console.log(countNodesInLoop(head));

Output
4

Time complexity: O(n), where n is the number of nodes in the Linked List.
Auxiliary Space: O(1)



Similar Reads

XOR Linked List - Reverse a Linked List in groups of given size
Given a XOR linked list and an integer K, the task is to reverse every K nodes in the given XOR linked list. Examples: Input: XLL = 7< – > 6 < – > 8 < – > 11 < – > 3, K = 3 Output: 8 < – > 6 < – > 7 < – > 3 < – > 11 Explanation: Reversing first K(= 3) nodes modifies the Linked List to 8 < – > 6
13 min read
XOR Linked List - Pairwise swap elements of a given linked list
Given a XOR linked list, the task is to pairwise swap the elements of the given XOR linked list . Examples: Input: 4 <-> 7 <-> 9 <-> 7Output: 7 <-> 4 <-> 7 <-> 9Explanation:First pair of nodes are swapped to formed the sequence {4, 7} and second pair of nodes are swapped to form the sequence {9, 7}. Input: 1 <
12 min read
Create new linked list from two given linked list with greater element at each node
Given two linked list of the same size, the task is to create a new linked list using those linked lists. The condition is that the greater node among both linked list will be added to the new linked list.Examples: Input: list1 = 5->2->3->8list2 = 1->7->4->5Output: New list = 5->7->4->8Input: list1 = 2->8->9->3li
8 min read
Length of longest palindrome list in a linked list using O(1) extra space
Given a linked list, find the length of the longest palindrome list that exists in that linked list. Examples: Input : List = 2->3->7->3->2->12->24 Output : 5 The longest palindrome list is 2->3->7->3->2 Input : List = 12->4->4->3->14 Output : 2 The longest palindrome list is 4->4Recommended PracticeLeng
9 min read
Javascript Program For Finding The Length Of Longest Palindrome List In A Linked List Using O(1) Extra Space
Given a linked list, find the length of the longest palindrome list that exists in that linked list. Examples: Input : List = 2->3->7->3->2->12->24 Output : 5 The longest palindrome list is 2->3->7->3->2 Input : List = 12->4->4->3->14 Output : 2 The longest palindrome list is 4->4A simple solution could
3 min read
Convert Singly Linked List to XOR Linked List
Prerequisite: XOR Linked List – A Memory Efficient Doubly Linked List | Set 1XOR Linked List – A Memory Efficient Doubly Linked List | Set 2 An XOR linked list is a memory efficient doubly linked list in which the next pointer of every node stores the XOR of previous and next node's address. Given a singly linked list, the task is to convert the gi
9 min read
XOR linked list- Remove first node of the linked list
Given an XOR linked list, the task is to remove the first node of the XOR linked list. Examples: Input: XLL = 4 < – > 7 < – > 9 < – > 7 Output: 7 < – > 9 < – > 7 Explanation: Removing the first node of the XOR linked list modifies XLL to 7 < – > 9 < – > 7 Input: XLL = NULL Output: List Is Empty Approach: Th
11 min read
Remove all occurrences of one Linked list in another Linked list
Given two linked lists head1 and head2, the task is to remove all occurrences of head2 in head1 and return the head1. Examples: Input: head1 = 2 -> 3 -> 4 -> 5 -> 3 -> 4, head2 = 3 -> 4Output: 2 -> 5Explanation: After removing all occurrences of 3 -> 4 in head1 output is 2 -> 5. Input: head1 = 3 -> 6 -> 9 -> 8 -
9 min read
Count occurrences of one linked list in another Linked List
Given two linked lists head1 and head2, the task is to find occurrences of head2 in head1. Examples: Input: Head1 = 1->2->3->2->4->5->2->4, Head2 = 2->4Output: Occurrences of head2 in head1: 2 Input: Head1 = 3->4->1->5->2, Head2 = 3->4Output: Occurrences of Head2 in Head1: 1 Approach 1: To solve the problem us
15 min read
When is Doubly Linked List more Efficient than Singly Linked List?
Did you know there are some cases where a Doubly Linked List is more efficient than a Singly Linked List, even though it takes more memory compared to a Singly Linked List? What are those Cases? Well, we will discuss that in the following article, But first, let's talk about Singly and linked lists: What is a Singly Linked List?A singly linked list
4 min read
XOR Linked List: Remove last node of the Linked List
Given an XOR linked list, the task is to delete the node at the end of the XOR Linked List. Examples: Input: 4<–>7<–>9<–>7Output: 4<–>7<–>9Explanation: Deleting a node from the end modifies the given XOR Linked List to 4<–>7<–>9 Input: 10Output: List is emptyExplanation: After deleting the only node present
15+ min read
Is two way linked list and doubly linked list same?
Yes, a two-way linked list and a doubly linked list are the same. Both terms refer to a type of linked list where each node contains a reference to the next node as well as the previous node in the sequence. The term “two-way” emphasizes the ability to move in both directions through the list, while “doubly” highlights that there are two links per
3 min read
XOR linked list: Reverse last K nodes of a Linked List
Given a XOR Linked List and a positive integer K, the task is to reverse the last K nodes in the given XOR linked list. Examples: Input: LL: 7 <–> 6 <–> 8 <–> 11 <–> 3 <–> 1, K = 3Output: 7<–>6<–>8<–>1<–>3<–>11 Input: LL: 7 <–> 6 <–> 8 <–> 11 <–> 3 <–> 1 <–
14 min read
XOR Linked List - A Memory Efficient Doubly Linked List | Set 1
In this post, we're going to talk about how XOR linked lists are used to reduce the memory requirements of doubly-linked lists. We know that each node in a doubly-linked list has two pointer fields which contain the addresses of the previous and next node. On the other hand, each node of the XOR linked list requires only a single pointer field, whi
15+ min read
Linked List of Linked List
Linked list of linke­d list, also known as nested linke­d lists, is a type of Linked List where each main node stores another full linked list. This structure­ beats old, plain linked lists. It gives way more­ flexibility to store and manage comple­x data. In this article we will learn about the basics of Linked List of Linked List, how to create L
9 min read
XOR Linked List – A Memory Efficient Doubly Linked List | Set 2
In the previous post, we discussed how a Doubly Linked can be created using only one space for the address field with every node. In this post, we will discuss the implementation of a memory-efficient doubly linked list. We will mainly discuss the following two simple functions. A function to insert a new node at the beginning.A function to travers
10 min read
Difference between Singly linked list and Doubly linked list
Introduction to Singly linked list : A singly linked list is a set of nodes where each node has two fields 'data' and 'link'. The 'data' field stores actual piece of information and 'link' field is used to point to next node. Basically the 'link' field stores the address of the next node.  Introduction to Doubly linked list : A Doubly Linked List (
2 min read
Check if a linked list is Circular Linked List
Given the head of a singly linked list, the task is to find if given linked list is circular or not. A linked list is called circular if its last node points back to its first node. Note: The linked list does not contain any internal loops. Example: Input: LinkedList: 2->4->6->7->5 Output: trueExplanation: As shown in figure the first a
12 min read
Javascript Program To Merge A Linked List Into Another Linked List At Alternate Positions
Given two linked lists, insert nodes of the second list into the first list at alternate positions of the first list. For example, if first list is 5->7->17->13->11 and second is 12->10->2->4->6, the first list should become 5->12->7->10->17->2->13->4->11->6 and second list should become empty. The
3 min read
Insert a linked list into another linked list
Given two linked lists, head1 and head2 of sizes m and n respectively. The task is to remove head1's nodes from the ath node to the bth node and insert head2 in their place. Examples: Input: a = 3, b = 4head1: 10 -> 11 -> 12 -> 13 -> 14 -> 15, head2: 100 -> 101 -> 102 -> 103Output: 10 -> 11 -> 12 -> 100 -> 101 -
10 min read
Convert singly linked list into circular linked list
Given a singly linked list, the task is to convert it into a circular linked list. Examples: Input: head: 1 -> 2 -> 3 -> 4 -> 5 -> 6 -> NULLOutput: Explanation: Singly linked list is converted to circular by pointing last node to head. Input: head: 2 -> 4 -> 6 -> 8 -> 10 -> 12 -> NULLOutput: Explanation: Singly l
11 min read
Merge a linked list into another linked list at alternate positions
Given two singly linked lists, The task is to insert nodes of the second list into the first list at alternate positions of the first list and leave the remaining nodes of the second list if it is longer. Example: Input: head1: 1->2->3 , head2: 4->5->6->7->8Output: head1: 1->4->2->5->3->6 , head2: 7->8 Input: hea
8 min read
Lexicographically smallest permutation of a string that can be reduced to length K by removing K-length prefixes from palindromic substrings of length 2K
Given a binary string str of length N, and an integer K, the task is to find the lexicographically smallest permutation of the string str that can be reduced to length K by removal of every K-length prefix from palindromic substrings of length 2K. If no such permutation exists, print "Not Possible". Examples: Input: str = "0000100001100001”, K = 4O
14 min read
Find the Max sum of Subarray of length K in a Linked List
Given a linked list of integers and a number K, find the maximum sum of a subarray of length K. Examples: Input: List = 1 -> -2 -> 3 -> 4 -> -1 -> 2, K = 3Output: 6Explanation: The sum of subarray 3 -> 4 -> -1 is 6 which is the maximum sum of a subarray of length K = 3 Input: List = -1 -> 2 -> 3 -> -4 -> 5 -> 6,
15+ min read
Find the Max product Sublist of length K in a Linked list
Given a linked list of integers and a number K, find the maximum product of a sublist of length K in a linked list. Examples: Input: List: 1 -> -2 -> -3 -> 4 -> -5, K = 3Output: 60Explanation: The product of sublist -3 -> 4 -> -5 is 60 which is the maximum product of a sublist of length K = 3. Input: List: 2 -> 4 -> 6 ->
13 min read
Find Length of a Linked List (Iterative and Recursive)
Given a Singly Linked List, the task is to find the Length of the Linked List. Examples: Input: LinkedList = 1->3->1->2->1Output: 5 Input: LinkedList = 2->4->1->9->5->3->6Output: 7 Iterative Approach to Find the Length of a Linked List:The idea is similar to traversal of Linked List with an additional variable to count
11 min read
Check whether the length of given linked list is Even or Odd
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 : OddRecommended: Please solve it on "PRACTICE" first, before moving on to the solution. Method 1: Count the codes linea
6 min read
Javascript Program To Check Whether The Length Of Given Linked List Is Even Or Odd
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->NULLOutput : EvenInput : 1->2->3->4->5->NULLOutput : OddMethod 1: Count the codes linearly Traverse the entire Linked List and keep counting the number of nodes. As soon as t
3 min read
Find the length of the median of a Triangle if length of sides are given
Given the length of all three sides of a triangle as a, b and c. The task is to calculate the length of the median of the triangle.  A median of a triangle is a line segment joining a vertex to the midpoint of the opposite side, thus bisecting that side.   Examples:   Input: a = 8, b = 10, c = 13 Output: 10.89Input: a = 4, b = 3, c = 5 Output: 3.61
4 min read
Maximum XOR sublist of length K in Linked list
Given a linked list of integers and an integer value K, the task is to find the maximum XOR value of a sublist of length K in the linked list. Examples: Input: 4 -> 6 -> 9 -> 7, K = 2Output: 15Explanation: All possible sublists of length K = 2 starting from each node.4 -> 6, 6 -> 9, 9 -> 7The XOR value of each sublist is:4 -> 6
10 min read
Article Tags :
Practice Tags :