Professional Documents
Culture Documents
[DATE]
MUDABBAR UL ISLAM
SP18-BSE-118
Q4: a) Write a program to find the number of nodes in the linked list using recursion.
#include<iostream>
using namespace std;
struct node{
int data;
node* next;
};
node*head;
int nodes(node*pt);
void insert_at_start(int value);
int main(){
head=NULL;
int value, opt;
node * pt;
do
{
cout<<"\n Press 1 to insert at start";
cout<<"\n press 2 to find number of nodes";
cout<<"\n press 0 to exit ";
cout<<"\n Enter option: ";
cin>>opt;
switch(opt){
case 1:
cout<<"enter the value :"<<endl;
cin>>value;
insert_at_start(value);
break;
case 2:
pt=head;
cout<<"total nodes are "<<nodes(pt)<<endl;
break;
case 0:
cout<<"\n you selected exit option";
break;
default:
cout<<"\n wrong option";
}
}while(opt!=0);
return 1;
}
void insert_at_start(int value){
node*temp=new node;
temp->data=value;
temp->next=NULL;
if(head==NULL){
head=temp;
}
else{
cout<<"in else"<<endl;
temp->next=head;
head=temp;
}
}
int nodes(node*pt){ //nodes function count nodes recursively
if (pt==NULL){ //Base case
return 0;
}
return 1+nodes(pt->next); // function calling itself and returning value in main.
}
b) Write a program to compare two linked list using recursion
//this is only the function for comparing two lists .
bool compare(node* A,node* B){
if (A==NULL && B==NULL){ //base case when both list reach to end
return true;
}
if (a != NULL && b != NULL) {
c) Write a program to add a new node at the end of linked list using recursion.
#include<iostream>
using namespace std;
struct node{
int data;
node* next;
};
node*head;
int nodes(node*pt);
void insert_at_end(node*pt,int value);
int main(){
head=NULL;
}while(opt!=0);
return 1;
}
if(pt==NULL){
pt=new node;
pt->data=value;
pt->next=NULL;
}
else{
insert_at_end(pt->next,value);
}
}
int nodes(node*pt){
if (pt==NULL){
return 0;
}
return 1+nodes(pt->next);
}