Code:
#include<iostream>
using namespace std;
struct node {
int data;
struct node* next;
};
struct node* BuildOneTwoThree(){
struct node* head=NULL;
struct node* second=NULL;
struct node* third=NULL;
head= new struct node,second= new struct node,third= new struct node;
head->next=second,second->next=third,third->next=NULL;
head->data=1,head->next->data=2,head->next->next->data=3;
return head;
};
int counter=0;
int length(struct node* list) {
if(list!=NULL) {
counter+=1;
length(list->next);
}
return counter;
}
int main(){
struct node* list=BuildOneTwoThree();
cout<<"Length of List: "<<length(list)<<endl;
system("pause");
return 0;
}
is there any way not to use a global variable with this recursive function
Code:
int counter=0;
int length(struct node* list) {
if(list!=NULL) {
counter++;
length(list->next);
}
return counter;
}