Home > Backend Development > C++ > body text

C program to find length of linked list

PHPz
Release: 2023-09-07 19:33:01
forward
1025 people have browsed it

Linked lists use dynamic memory allocation, i.e. they grow and shrink accordingly. They are defined as collections of nodes. Here, a node has two parts, data and links. The representation of data, links and linked lists is as follows -

C program to find length of linked list

Types of linked lists

There are four types of linked lists, as follows: -

  • Singly linked list/Singly linked list
  • Double/double linked list
  • Cycling singly linked list
  • Cycling double linked list

We use the recursive method to find the length of the linked list The logic is -

int length(node *temp){
   if(temp==NULL)
      return l;
   else{
      l=l+1;
      length(temp->next);
   }
}
Copy after login

Program

The following is a C program to find the length of a linked list-

Live demonstration

#include 
#include 
typedef struct linklist{
   int data;
   struct linklist *next;
}node;
int l=0;
int main(){
   node *head=NULL,*temp,*temp1;
   int len,choice,count=0,key;
   do{
      temp=(node *)malloc(sizeof(node));
      if(temp!=NULL){
         printf("

enter the elements in a list : "); scanf("%d",&temp->data); temp->next=NULL; if(head==NULL){ head=temp; }else{ temp1=head; while(temp1->next!=NULL){ temp1=temp1->next; } temp1->next=temp; } }else{ printf("

Memory is full"); } printf("

press 1 to enter data into list: "); scanf("%d",&choice); }while(choice==1); len=length(head); printf("The list has %d no of nodes",l); return 0; } //recursive function to find length int length(node *temp){ if(temp==NULL) return l; else{ l=l+1; length(temp->next); } }

Copy after login

Output

When When executing the above program, the following results are produced -

Run 1:
enter the elements in a list: 3
press 1 to enter data into list: 1
enter the elements in a list: 56
press 1 to enter data into list: 1
enter the elements in a list: 56
press 1 to enter data into list: 0
The list has 3 no of nodes
Run 2:
enter the elements in a list: 12
press 1 to enter data into list: 1
enter the elements in a list: 45
press 1 to enter data into list: 0
The list has 2 no of nodes
Copy after login

The above is the detailed content of C program to find length of linked list. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!