SCHOOL OF CODE BUILDERS
Learn To CODE. Become A DEVELOPER.
Pages
HOME
DATA STRUCTURES
STRINGS
ARRAYS
MATRIX
BINARY TREES
LINKED LIST
STACK
QUEUE
SORTING
SEARCHING
C
PYTHON
PSEUDOCODE
CONTEST PROBLEMS
ALGORITHMS
PATTERNS
PHP
C PUZZLES
C INTERVIEW QUESTIONS
JAVA
C++
HASHING
RECURSION
BASIC C PROGRAMS
TCS-CODEVITA
FACEBOOK
CONTACT US
Linked List Implementation(find the length of the linked list iterative)
Linked List Implementation(find the length of the linked list iterative)
Implementation:
#include
#include
/* structure of the node in the linked list */ struct node { int data; struct node *next; }; /* function to create a new node in the linked list */ struct node* newnode(int data) { struct node *new=(struct node*)malloc(sizeof(struct node)); new->data=data; new->next=NULL; return new; } /* function to insert every node in the tail of the linked list */ void insertastail(struct node **head,int data) { struct node *temp; struct node *current=*head; if(current==NULL) { *head=newnode(data); } else { temp=newnode(data); while(current->next!=NULL) current=current->next; current->next=temp; } } /* function to print the elements of the linked list */ void printlist(struct node *head) { struct node *current=head; while(current!=NULL) { printf("%d ",current->data); current=current->next; } } /* function to find the length of the linked list iteratively */ int findlength(struct node *head) { int length=0; if(head==NULL) return 0; else { while(head!=NULL) { length++; head=head->next; } return length; } } int main(void) { struct node *head=NULL; int data; int i,n; scanf("%d",&n); for(i=1;i<=n;i++) insertastail(&head,i); printlist(head); printf("\n%d",findlength(head)); return 0; }
PREVIOUS
NEXT
HOME