To find the length of a Singly Linked List.
Create a temp pointer and an integer variable len - find length of list.
Initialize temp with head and len with 0(zero).
Move temp from one node to another until it becomes NULL.
Increment len variable in every iteration.
int lengthOfList(){
struct node *temp;
int len = 0;
temp = head;
while(temp!=NULL){
len++;
temp = temp->next;
}
return len;
}
View Full Code
#include<stdio.h>
#include<stdlib.h>
void create();
int lengthOfList();
void traverse();
struct node{
int data;
struct node *next;
};
struct node *head=NULL;
int main(){
int opt;
printf("::Single Linked List Operations::\n1.Creation\n2.Length\n3.Traversing\n4.Exit");
do{
printf("\nSelect operation:\n");
scanf("%d",&opt);
switch(opt){
case 1:
create();
break;
case 2:
printf("Length of Singly Linked List is %d",lengthOfList());
break;
case 3:
traverse();
break;
case 4:
exit(0);
break;
default:
printf("Invalid operation.\n");
}
}while(opt!=4);
return 0;
}
void create(){
int ch;
struct node *newNode,*lastNode;
lastNode=(struct node*)malloc(sizeof(struct node*));
do{
newNode=(struct node*)malloc(sizeof(struct node*));
printf("Enter node value:\n");
scanf("%d",&newNode->data);
if(head==NULL)
head=newNode;
lastNode->next=newNode;
lastNode=newNode;
printf("To continue press 1 otherwise 0:\n");
scanf("%d",&ch);
}while(ch==1);
lastNode->next=NULL;
}
int lengthOfList(){
struct node *temp;
int len = 0;
temp = head;
while(temp!=NULL){
len++;
temp = temp->next;
}
return len;
}
void traverse(){
struct node *ptr;
if(head==NULL){
printf("List is empty.\n");
}else{
ptr=head;
while(ptr!=NULL){
printf("%d->",ptr->data);
ptr=ptr->next;
}
printf("NULL");
}
}
Related Programs
Create Singly Linked List with N number of nodes and display.
Perform insertion operation on Singly Linked List.
Perform deletion operation on Singly Linked List.
Reverse of Singly Linked List.
Move last node of Singly Linked List to first.
Swap first and last nodes in a Singly Linked List.
Find the length of Singly Linked List.
Find middle node of Singly Linked List