You are on page 1of 6

DSA LAB ASSINGMENT 2

To: Mr Tanveer ahmed

[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) {

return (A->data == B->data) && // compareing both node's data


compare(A->next, B->next); // recall function with nodes moving to next
}
// If one of the lists
// is empty and other is not then
return false;
}

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;

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;
pt=head;
insert_at_end(pt,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_end(node*pt,int value){

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);
}

You might also like