Find Length of a Linked List (Iterative)

882.3K Views
Answered

Write a C function to count number of nodes in a given singly linked list.

For example, the function should return 6 for linked list 1->3->1->4->2->1.

Share
Add Comment

  • 1 Answer(s)
    Best answer

    ITERATIVE SOLUTION-

     /*
     * File:   main.cpp
     * Author: akash
     *
     * Created on 12 August, 2015, 4:57 PM
     */
    #include <stdio.h>
     #include <stdlib.h>
    struct node
     {
     int data;
     struct node* next;
     };
     //void push(struct **node top_head,int dataToEnter);
     //int getCount(struct *node top_head);
    void push(struct node** top_head,int dataToEnter)
     {
     struct node* add_node = (struct node*) malloc(sizeof(struct node));
    add_node->data = dataToEnter;
     add_node->next = (*top_head);
     (*top_head) = add_node;
     }
    int getCount(struct node* top_head){
     if (top_head == NULL)
     return 0;
    // count is 1 + count of remaining list
     return 1 + getCount(top_head->next);
     }
    int main(){
     struct node* head = NULL;
    push(&head, 10);
     push(&head, 20);
     push(&head, 30);
     push(&head, 40);
     push(&head, 20);
     push(&head, 30);
    printf("Nodes Count is %d", getCount(head));
     return 0;
     }
     

    SherlockHolmes Expert Answered on 13th August 2015.
    Add Comment
  • Your Answer

    By posting your answer, you agree to the privacy policy and terms of service.
  • More puzzles to try-