top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

Write a Algorithm that counts number of nodes in the circular linked list?

+2 votes
3,332 views
Write a Algorithm that counts number of nodes in the circular linked list?
posted Mar 1, 2016 by Mohammed Hussain

Share this question
Facebook Share Button Twitter Share Button LinkedIn Share Button

3 Answers

+1 vote

Just move one node in a iteration till start node is next node and each iteration increase the count by one.

void count(struct node *last)  //last is the last node
{
    struct node *p;
    int count_node=0;

    if(last==NULL)
    {
       printf("list empty\n");
       return;
    }
    p=last->link;

    do
    {
       count_node++;
       p=p->link;
    }while(p!=last->link);

    printf("\nNo of nodes=%d",count_node);
}
answer Mar 1, 2016 by Josita Sarwan
0 votes

here count gives no of nodes in that list

struct node
{  int data;
   struct node *next;
};
i write just function here
int count(struct node *pp)
{  struct node *start;
  int count=0;
   start=pp->next;
  while(start->next!=pp)
  { start=start->next;  
   count++; }
  return count;
}
answer Mar 2, 2016 by Manikandan J
This code will give segmentation fault.If list is empty because you did not check empty case of list
0 votes
int countNode(struct node*List)
{
struct node*firstNode=List; 
int count=0;
if(List==NULL)
return 0;
while(List->next!=firstNode)
count++,List=List->next;
return coutn;
}
answer Mar 20, 2016 by Rajan Paswan
Similar Questions
+1 vote

What is the best logic or way to detected linked list has loop ?
And also what is the best way to find out that given linked list is circular ?

+2 votes

I am looking for sample code which can impress an interviewer.

–1 vote

Given a Singly linked list with each node containing either 0, 1 or 2. Write code to sort the list.
Input : 1 -> 1 -> 2 -> 0 -> 2 -> 0 -> 1 -> 0
Output : 0 -> 0 -> 0 -> 1 -> 1 -> 1 -> 2 -> 2

...