Find the length of circular linked list

Circular linked list always contain a loop. Here last node next field are store information about first node of linked list. Our goal is to count number of nodes are exist in this linked list.

Here given code implementation process.

//C Program 
//Find the length of circular linked list
#include <stdio.h>

#include <stdlib.h> //for malloc function

//Create structure
struct Node
{
  int data;
  struct Node *next;
};
//insert Node element at end of linked list
void insert(struct Node **head, int value)
{
  //Create dynamic node
  struct Node *node = (struct Node *) malloc(sizeof(struct Node));
  if (node == NULL)
  {
    printf("Memory overflow\n");
  }
  else
  {
    node->data = value;
    node->next = *head;
    if ( *head == NULL)
    {
      *head = node;
      node->next = *head;
    }
    else
    {
      struct Node *temp = *head;
      while (temp->next != *head)
      {
        temp = temp->next;
      }
      //Add node at last
      temp->next = node;
    }
  }
}
//Display element of Node
void display(struct Node *head)
{
  if (head == NULL)
  {
    printf("Empty linked list");
  }
  else
  {
    printf("\n Linked List Element :");
    struct Node *temp = head;
    do {
      printf("  %d", temp->data);
      temp = temp->next;
    } while (temp != NULL && temp != head);
  }
}
//Function which is count the number of nodes in linked list
int find_length(struct Node *head)
{
  //Variable which is used to hold nodes size
  //Set the counter value zero
  int counter = 0;
  struct Node *temp = head;
  //This loop is iterating linked list node from front to rear
  do {
    //Increase node count value by one
    counter++;
    //Visit to next node
    temp = temp->next;
  }
  while (temp != NULL && temp != head);
  //return the value of number of nodes
  return counter;
}
int main()
{
  //create node pointer
  struct Node *head = NULL;
  //insert element of linked list
  insert( & head, 1);
  insert( & head, 2);
  insert( & head, 3);
  insert( & head, 4);
  insert( & head, 5);
  insert( & head, 6);
  insert( & head, 7);
  insert( & head, 9);
  //display all node
  display(head);
  printf("\n Length : %d\n", find_length(head));
  return 0;
}

Output

 Linked List Element :  1  2  3  4  5  6  7  9
 Length : 8
/*
  Java Program
  Merge two sorted doubly linked list
*/
class Node
{
  public int data;
  public Node next;
  public Node(int value)
  {
    //Setup initial values of linked list node
    this.data = value;
    this.next = null;
  }
}
class MyLinkedList
{
  public Node head;
  public MyLinkedList()
  {
    head = null;
  }
  //insert Node element at end of linked list
  public void insert(int value)
  {
    //Create dynamic node
    Node node = new Node(value);
    if (node == null)
    {
      System.out.print("Memory overflow\n");
    }
    else
    {
         
      if (head == null)
      {
        head = node;
        node.next = head;
      }
      else
      {
                node.next = head;
        Node temp = head;
        while (temp.next != head)
        {
          temp = temp.next;
        }
        //Add node at last
        temp.next = node;
      }
    }
  }
  //Display element of Node
  public void display()
  {
    if (head == null)
    {
      System.out.print("Empty linked list");
    }
    else
    {
      System.out.print("\n Linked List Element :");
      Node temp = head;
      do {
        System.out.print(" "+ temp.data);
        temp = temp.next;
      }
      while (temp != null && temp != head);
    }
  }
  //Function which is count the number of nodes in linked list
  public int find_length()
  {
    //Variable which is used to hold nodes size
    //Set the counter value zero
    int counter = 0;
    Node temp = head;
    //This loop is iterating linked list node from front to rear
    do {
      //Increase node count value by one
      counter++;
      //Visit to next node
      temp = temp.next;
    }
    while (temp != null && temp != head);
    //return the value of number of nodes
    return counter;
  }
  public static void main(String[] args)
  {
    MyLinkedList obj = new MyLinkedList();
    //insert element of linked list
    obj.insert(1);
    obj.insert(2);
    obj.insert(3);
    obj.insert(4);
    obj.insert(5);
    obj.insert(6);
    obj.insert(7);
    obj.insert(9);
    //display all node
    obj.display();
    int length = obj.find_length();
    System.out.print("\n Length : " + length + "\n");
  }
}

Output

 Linked List Element : 1 2 3 4 5 6 7 9
 Length : 8
/*
  C++ Program
  Merge two sorted doubly linked list
*/
#include<iostream>

using namespace std;
class Node
{
  public: int data;
  Node * next;
  Node(int value)
  {
    //Setup initial values of linked list node
    this->data = value;
    this->next = NULL;
  }
};
class MyLinkedList
{
  public: 
    Node * head;
  MyLinkedList()
  {
    this->head = NULL;
  }
  //insert Node element at end of linked list
  void insert(int value)
  {
    //Create dynamic node
    Node * node = new Node(value);
    if (node == NULL)
    {
      cout << "Memory overflow\n";
    }
    else
    {
      if (this->head == NULL)
      {
        this->head = node;
        node->next = this->head;
      }
      else
      {
        node->next = this->head;
        Node * temp = this->head;
        while (temp->next != this->head)
        {
          temp = temp->next;
        }
        //Add node at last
        temp->next = node;
      }
    }
  }
  //Display element of Node
  void display()
  {
    if (this->head == NULL)
    {
      cout << "Empty linked list";
    }
    else
    {
      cout << "\n Linked List Element :";
      Node * temp = this->head;
      do {
        cout << " " << temp->data;
        temp = temp->next;
      } while (temp != NULL && temp != this->head);
    }
  }
  //Function which is count the number of nodes in linked list
  int find_length()
  {
    //Variable which is used to hold nodes size
    //Set the counter value zero
    int counter = 0;
    Node * temp = this->head;
    //This loop is iterating linked list node from front to rear
    do {
      //Increase node count value by one
      counter++;
      //Visit to next node
      temp = temp->next;
    } while (temp != NULL && temp != this->head);
    return
    //return the value of number of nodes
    counter;
  }
};
int main()
{
  MyLinkedList obj = MyLinkedList();
  //insert element of linked list
  obj.insert(1);
  obj.insert(2);
  obj.insert(3);
  obj.insert(4);
  obj.insert(5);
  obj.insert(6);
  obj.insert(7);
  obj.insert(9);
  //display all node
  obj.display();
  int length = obj.find_length();
  cout << "\n Length : " << length << "\n";
  return 0;
}

Output

 Linked List Element : 1 2 3 4 5 6 7 9
 Length : 8
/*
  C# Program
  Merge two sorted doubly linked list
*/
using System;
class Node
{
  public int data;
  public Node next;
  public
  Node(int value)
  {
    //Setup initial values of linked list node
    this.data = value;
    this.next = null;
  }
}
class MyLinkedList
{
  public Node head;
  public
  MyLinkedList()
  {
    head = null;
  }
  //insert Node element at end of linked list
  public void insert(int value)
  {
    //Create dynamic node
    Node node = new Node(value);
    if (node == null)
    {
      Console.Write("Memory overflow\n");
    }
    else
    {
      if (head == null)
      {
        head = node;
        node.next = head;
      }
      else
      {
        node.next = head;
        Node temp = head;
        while (temp.next != head)
        {
          temp = temp.next;
        }
        //Add node at last
        temp.next = node;
      }
    }
  }
  //Display element of Node
  public void display()
  {
    if (head == null)
    {
      Console.Write("Empty linked list");
    }
    else
    {
      Console.Write("\n Linked List Element :");
      Node temp = head;
      do {
        Console.Write(" " + temp.data);
        temp = temp.next;
      } while (temp != null && temp != head);
    }
  }
  //Function which is count the number of nodes in linked list
  public int find_length()
  {
    //Variable which is used to hold nodes size
    //Set the counter value zero
    int counter = 0;
    Node temp = head;
    //This loop is iterating linked list node from front to rear
    do {
      //Increase node count value by one
      counter++;
      //Visit to next node
      temp = temp.next;
    } while (temp != null && temp != head);
    return counter;
  }
  public static void Main(String[] args)
  {
    MyLinkedList obj = new MyLinkedList();
    //insert element of linked list
    obj.insert(1);
    obj.insert(2);
    obj.insert(3);
    obj.insert(4);
    obj.insert(5);
    obj.insert(6);
    obj.insert(7);
    obj.insert(9);
    //display all node
    obj.display();
    int length = obj.find_length();
    Console.Write("\n Length : " + length + "\n");
  }
}

Output

 Linked List Element : 1 2 3 4 5 6 7 9
 Length : 8
<?php
/*
  Php Program
  Merge two sorted doubly linked list
*/
class Node
{
  public $data;
  public $next;

  function __construct($value)
  {
    //Setup initial values of linked list node
    $this->data = $value;
    $this->next = null;
  }
}
class MyLinkedList
{
  public $head;

  function __construct()
  {
    $this->head = null;
  }
  //insert Node element at end of linked list
  public  function insert($value)
  {
    //Create dynamic node
    $node = new Node($value);
    if ($node == null)
    {
      echo("Memory overflow\n");
    }
    else
    {
      if ($this->head == null)
      {
        $this->head = $node;
        $node->next = $this->head;
      }
      else
      {
        $node->next = $this->head;
        $temp = $this->head;
        while ($temp->next != $this->head)
        {
          $temp = $temp->next;
        }
        //Add node at last
        $temp->next = $node;
      }
    }
  }
  //Display element of Node
  public  function display()
  {
    if ($this->head == null)
    {
      echo("Empty linked list");
    }
    else
    {
      echo("\n Linked List Element :");
      $temp = $this->head;
      do {
        echo(" ". $temp->data);
        $temp = $temp->next;
      } while ($temp != null && $temp != $this->head);
    }
  }
  //Function which is count the number of nodes in linked list
  public  function find_length()
  {
    //Variable which is used to hold nodes size
    //Set the counter value zero
    $counter = 0;
    $temp = $this->head;
    //This loop is iterating linked list node from front to rear
    do {
      //Increase node count value by one
      $counter++;
      //Visit to next node
      $temp = $temp->next;
    } while ($temp != null && $temp != $this->head);
    return $counter;
  }
}

function main()
{
  $obj = new MyLinkedList();
  //insert element of linked list
  $obj->insert(1);
  $obj->insert(2);
  $obj->insert(3);
  $obj->insert(4);
  $obj->insert(5);
  $obj->insert(6);
  $obj->insert(7);
  $obj->insert(9);
  //display all node
  $obj->display();
  $length = $obj->find_length();
  echo("\n Length : ". $length ."\n");
}
main();

Output

 Linked List Element : 1 2 3 4 5 6 7 9
 Length : 8
/*
  Node Js Program
  Merge two sorted doubly linked list
*/
class Node
{
  constructor(value)
  {
    //Setup initial values of linked list node
    this.data = value;
    this.next = null;
  }
}
class MyLinkedList
{
  constructor()
  {
    this.head = null;
  }
  //insert Node element at end of linked list
  insert(value)
  {
    //Create dynamic node
    var node = new Node(value);
    if (node == null)
    {
      process.stdout.write("Memory overflow\n");
    }
    else
    {
      if (this.head == null)
      {
        this.head = node;
        node.next = this.head;
      }
      else
      {
        node.next = this.head;
        var temp = this.head;
        while (temp.next != this.head)
        {
          temp = temp.next;
        }
        //Add node at last
        temp.next = node;
      }
    }
  }
  //Display element of Node
  display()
  {
    if (this.head == null)
    {
      process.stdout.write("Empty linked list");
    }
    else
    {
      process.stdout.write("\n Linked List Element :");
      var temp = this.head;
      do {
        process.stdout.write(" " + temp.data);
        temp = temp.next;
      }
      while (temp != null && temp != this.head);
    }
  }
  //Function which is count the number of nodes in linked list
  find_length()
  {
    //Variable which is used to hold nodes size
    //Set the counter value zero
    var counter = 0;
    var temp = this.head;
    //This loop is iterating linked list node from front to rear
    do {
      //Increase node count value by one
      counter++;
      //Visit to next node
      temp = temp.next;
    }
    while (temp != null && temp != this.head);
    return counter;
  }
}

function main(args)
{
  var obj = new MyLinkedList();
  //insert element of linked list
  obj.insert(1);
  obj.insert(2);
  obj.insert(3);
  obj.insert(4);
  obj.insert(5);
  obj.insert(6);
  obj.insert(7);
  obj.insert(9);
  //display all node
  obj.display();
  var length = obj.find_length();
  process.stdout.write("\n Length : " + length + "\n");
}
main();

Output

 Linked List Element : 1 2 3 4 5 6 7 9
 Length : 8
# Python 3 Program
# Merge two sorted doubly linked list

class Node :
  
  def __init__(self, value) :
    # Setup initial values of linked list node
    self.data = value
    self.next = None
  

class MyLinkedList :
  
  def __init__(self) :
    self.head = None
  
  # insert Node element at end of linked list
  def insert(self, value) :
    # Create dynamic node
    node = Node(value)
    if (node == None) :
      print("Memory overflow\n", end = "")
    else :
      if (self.head == None) :
        self.head = node
        node.next = self.head
      else :
        node.next = self.head
        temp = self.head
        while (temp.next != self.head) :
          temp = temp.next
        
        # Add node at last
        temp.next = node
      
    
  
  # Display element of Node
  def display(self) :
    if (self.head == None) :
      print("Empty linked list", end = "")
    else :
      print("\n Linked List Element :", end = "")
      temp = self.head
      status = True
      while (temp != None and status == True) :
        print(" ", temp.data, end = "")
        temp = temp.next
        if (temp == self.head) :
          status = False
        
      
    
  
  # Function which is count the number of nodes in linked list
  def find_length(self) :
    # Variable which is used to hold nodes size
    # Set the counter value zero
    counter = 0
    temp = self.head
    status = True
    # This loop is iterating linked list node from front to rear
    while (temp != None and status == True) :
      # Increase node count value by one
      counter += 1
      # Visit to next node
      temp = temp.next
      if (temp == self.head) :
        status = False
      
    
    return counter
  

def main() :
  obj = MyLinkedList()
  # insert element of linked list
  obj.insert(1)
  obj.insert(2)
  obj.insert(3)
  obj.insert(4)
  obj.insert(5)
  obj.insert(6)
  obj.insert(7)
  obj.insert(9)
  # display all node
  obj.display()
  length = obj.find_length()
  print("\n Length : ", length ,"\n", end = "")


if __name__ == "__main__": main()

Output

 Linked List Element :  1  2  3  4  5  6  7  9
 Length :  8
# Ruby Program
# Merge two sorted doubly linked list

class Node
# Define the accessor and reader of class Node
  attr_reader :data, :next
  attr_accessor :data, :next

  
  def initialize(value)
  
    # Setup initial values of linked list node
    self.data = value
    self.next = nil
  end
end
class MyLinkedList
  # Define the accessor and reader of class MyLinkedList
  attr_reader :head
  attr_accessor :head

  
  def initialize()
  
    @head = nil
  end
  # insert Node element at end of linked list
  def insert(value)
  
    # Create dynamic node
    node = Node.new(value)
    if (node == nil)
    
      print("Memory overflow\n")
    else 
            if (@head == nil)
      
        @head = node
        node.next = @head
      else
      
        node.next = @head
        temp = @head
        while (temp.next != @head)
        
          temp = temp.next
        end
        # Add node at last
        temp.next = node
      end
    end
  end
  # Display element of Node
  def display()
  
    if (@head == nil)
    
      print("Empty linked list")
    else
    
      print("\n Linked List Element :")
      temp = @head
      status = true
      while (temp != nil && status == true)
      
        print(" ", temp.data)
        temp = temp.next
        if (temp == @head)
        
          status = false
        end
      end
    end
  end
  # Function which is count the number of nodes in linked list
  def find_length()
  
    # Variable which is used to hold nodes size
    # Set the counter value zero
    counter = 0
    temp = @head
    status = true
    # This loop is iterating linked list node from front to rear
    while (temp != nil && status == true)
    
      # Increase node count value by one
      counter += 1
      # Visit to next node
      temp = temp.next
      if (temp == @head)
      
        status = false
      end
    end
    return counter
  end
end
def main()

  obj = MyLinkedList.new()
  # insert element of linked list
  obj.insert(1)
  obj.insert(2)
  obj.insert(3)
  obj.insert(4)
  obj.insert(5)
  obj.insert(6)
  obj.insert(7)
  obj.insert(9)
  # display all node
  obj.display()
  length = obj.find_length()
  print("\n Length : ", length ,"\n")
end
main()

Output

 Linked List Element : 1 2 3 4 5 6 7 9
 Length : 8
/*
Scala Program
Merge two sorted doubly linked list
*/
class Node(var data: Int,
  var next: Node)
{
  def this(value: Int)
  {
    //Setup initial values of linked list node
    this(value, null);
  }
}
class MyLinkedList(var head: Node)
{
  def this()
  {
    this(null);
  }
  //insert Node element at end of linked list
  def insert(value: Int): Unit = {
    //Create dynamic node
    var node: Node = new Node(value);
    if (node == null)
    {
      print("Memory overflow\n");
    }
    else
    {
      if (head == null)
      {
        head = node;
        node.next = head;
      }
      else
      {
        node.next = head;
        var temp: Node = head;
        while (temp.next != head)
        {
          temp = temp.next;
        }
        //Add node at last
        temp.next = node;
      }
    }
  }
  //Display element of Node
  def display(): Unit = {
    if (head == null)
    {
      print("Empty linked list");
    }
    else
    {
      print("\n Linked List Element :");
      var temp: Node = head;
      var status: Boolean = true;
      while (temp != null && status == true)
      {
        print(" " + temp.data);
        temp = temp.next;
        if (temp == head)
        {
          status = false;
        }
      }
    }
  }
  //Function which is count the number of nodes in linked list
  def find_length(): Int = {
    //Variable which is used to hold nodes size
    //Set the counter value zero
    var counter: Int = 0;
    var temp: Node = head;
    var status: Boolean = true;
    //This loop is iterating linked list node from front to rear
    while (temp != null && status == true)
    {
      //Increase node count value by one
      counter += 1;
      //Visit to next node
      temp = temp.next;
      if (temp == head)
      {
        status = false;
      }
    }
    return counter;
  }
}
object Main
{
  def main(args: Array[String]): Unit = {
    var obj: MyLinkedList = new MyLinkedList();
    //insert element of linked list
    obj.insert(1);
    obj.insert(2);
    obj.insert(3);
    obj.insert(4);
    obj.insert(5);
    obj.insert(6);
    obj.insert(7);
    obj.insert(9);
    //display all node
    obj.display();
    var length: Int = obj.find_length();
    print("\n Length : " + length + "\n");
  }
}

Output

 Linked List Element : 1 2 3 4 5 6 7 9
 Length : 8
/*
Swift Program
Merge two sorted doubly linked list
*/
class Node
{
  var data: Int;
  var next: Node? ;
  init(_ value: Int)
  {
    //Setup initial values of linked list node
    self.data = value;
    self.next = nil;
  }
}
class MyLinkedList
{
  var head: Node? ;
  init()
  {
    self.head = nil;
  }
  //insert Node element at end of linked list
  func insert(_ value: Int)
  {
    //Create dynamic node
    let node: Node? = Node(value);
    if (node == nil)
    {
      print("Memory overflow\n", terminator: "");
    }
    else
    {
      if (self.head == nil)
      {
        self.head = node;
        node!.next = self.head;
      }
      else
      {
        node!.next = self.head;
        var temp: Node? = self.head;
        while (temp != nil && !(temp!.next === self.head))
        {
          temp = temp!.next;
        }
        //Add node at last
        temp!.next = node;
      }
    }
  }
  //Display element of Node
  func display()
  {
    if (self.head == nil)
    {
      print("Empty linked list", terminator: "");
    }
    else
    {
      print("\n Linked List Element :", terminator: "");
      var temp: Node? = self.head;
      var status: Bool = true;
      while (temp != nil && status == true)
      {
        print(" ", temp!.data, terminator: "");
        temp = temp!.next;
        if (temp === self.head)
        {
          status = false;
        }
      }
    }
  }
  //Function which is count the number of nodes in linked list
  func find_length() -> Int
  {
    //Variable which is used to hold nodes size
    //Set the counter value zero
    var counter: Int = 0;
    var temp: Node? = self.head;
    var status: Bool = true;
    //This loop is iterating linked list node from front to rear
    while (temp != nil && status == true)
    {
      //Increase node count value by one
      counter += 1;
      //Visit to next node
      temp = temp!.next;
      if (temp === self.head)
      {
        status = false;
      }
    }
    return counter;
  }
}
func main()
{
  let obj: MyLinkedList = MyLinkedList();
  //insert element of linked list
  obj.insert(1);
  obj.insert(2);
  obj.insert(3);
  obj.insert(4);
  obj.insert(5);
  obj.insert(6);
  obj.insert(7);
  obj.insert(9);
  //display all node
  obj.display();
  let length: Int = obj.find_length();
  print("\n Length : ", length ,"\n", terminator: "");
}
main();

Output

 Linked List Element :  1  2  3  4  5  6  7  9
 Length :  8


Please share your knowledge to improve code and content standard. Also submit your doubts, and test case. We improve by your feedback. We will try to resolve your query as soon as possible.

New Comment







© 2021, kalkicode.com, All rights reserved