ronith
7/6/2018 - 5:00 PM

Find Length of a Linked List (Iterative and Recursive)

// // https://www.geeksforgeeks.org/find-length-of-a-linked-list-iterative-and-recursive/
#include <iostream>
#include <list>
using namespace std;

struct linked_list {
    int data;
    struct linked_list* next;
};
typedef struct linked_list node;
node* head;

void insert(int n) {
    node* list = (node*)malloc(sizeof(node*));
    list->data = n;
    list->next = head;
    head = list;
}

int length (node* list) {
    if (list == NULL)
        return 0;
    return 1+length(list->next);
}

int main () {
    int n;
    while(true) {
        cout<< "Enter the element, enter -9 to stop: ";
        cin>>n;
        if (n == -9)
            break;
        else
            insert(n);
    }
    n = length(head);
    cout<< "Length is "<< n;
}
// https://www.geeksforgeeks.org/find-length-of-a-linked-list-iterative-and-recursive/
#include <iostream>
#include <list>
using namespace std;

struct linked_list {
    int data;
    struct linked_list* next;
};
typedef struct linked_list node;
node* head;

void insert(int n) {
    node* list = (node*)malloc(sizeof(node*));
    list->data = n;
    list->next = head;
    head = list;
}

int main () {
    int n;
    head = NULL;
    while (true) {
        cout<< "Enter the element, enter -9 to stop: ";
        cin>>n;
        if (n==-9)
            break;
        else
            insert(n);
    }
    n = 0;
    node* list = head;
    while (list != NULL) {
        n++;
        list = list->next;
    }
    cout<< "Length of list is " << n;
}