Now let us write a function to count the number of nodes in a singly linked list.
This one is pretty simple.
The function starts with head node and loops till temp becomes NULL. Please remember that NULL has a numerical value of 0 and 0 is false and the condition (temp) is as good as saying (temp!=NULL).
How about a recursive function for the same?
Time to write the driver program for this function
This one is pretty simple.
- traverse the list from first node
- increment count after each node
- count at the end of traversal is the number of nodes
int get_count(NODEPTR temp) { int c = 0; while(temp) { c++; temp = temp->next; } return c; }
The function starts with head node and loops till temp becomes NULL. Please remember that NULL has a numerical value of 0 and 0 is false and the condition (temp) is as good as saying (temp!=NULL).
How about a recursive function for the same?
int get_count_recursive(NODEPTR temp) { if(temp!=NULL) { return get_count_recursive(temp->next)+1; } }
Time to write the driver program for this function
#include<stdio.h> #include<stdlib.h> struct node { int n; struct node *next; }; typedef struct node * NODEPTR; NODEPTR create_node(int value) { NODEPTR temp = (NODEPTR) malloc(sizeof(struct node)); temp->next = NULL; temp->n = value; return temp; } NODEPTR append_node(NODEPTR head, NODEPTR newnode) { NODEPTR temp = head; if(temp==NULL) return newnode; while(temp->next !=NULL) temp = temp->next; temp->next = newnode; return head; } void display_nodes(NODEPTR head) { NODEPTR temp = head;//redundant while (temp!= NULL) { printf("%d====>",temp->n); temp = temp->next; } printf("\n"); } int get_count(NODEPTR temp) { int c = 0; while(temp) { c++; temp = temp->next; } return c; } int get_count_recursive(NODEPTR temp) { if(temp!=NULL) { return get_count_recursive(temp->next)+1; } } int main() { NODEPTR head; NODEPTR newnode,dnode; //initialize head head = NULL; while(1){ int value; NODEPTR newnode; printf("node value (-1 to stop)="); scanf("%d",&value); if(value==-1) break; newnode = create_node(value); head = append_node(head,newnode); } printf("The linked list now is "); display_nodes(head); printf("The number of nodes in sll is %d\n",get_count(head)); printf("The number of nodes in sll using recursion is %d\n",get_count(head)); }
Comments
Post a Comment