Skip to content

Instantly share code, notes, and snippets.

@manojnaidu619
Last active July 1, 2019 17:27
Show Gist options
  • Save manojnaidu619/0b8d4e37532ce65a37e7a74e3c83b39d to your computer and use it in GitHub Desktop.
Save manojnaidu619/0b8d4e37532ce65a37e7a74e3c83b39d to your computer and use it in GitHub Desktop.
SLL in CPP
#include <iostream>
using namespace std;
struct Node {
int data;
struct Node *next;
}*start=NULL;
typedef struct Node node;
void insert(int a[], int n){
node *temp, *last;
start = new Node;
start->data = a[0];
start->next = NULL;
last = start;
for(int i=1;i<n;i++){
temp = new Node;
temp->data = a[i];
temp->next = NULL;
last->next = temp;
last = temp;
}
}
void display(node *p){
int count = 0;
while(p != NULL){
count++;
int data = p->data;
cout << data << " ";
p = p->next;
}
cout << endl << "Count : " << count << endl;
}
int rcount(node *p){
if(p){
return rcount(p->next)+1;
}else{
return 0;
}
}
void sum(node *p){
int sum=0;
while(p){
sum += p->data;
p = p->next;
}
cout << "Sum : " << sum << endl;
}
int rsum(node *p){
if(p == NULL){
return 0;
}else{
return (p->data) + rsum(p->next);
}
}
void max(node *p){
int max = p->data;
while(p){
if(p->data > max){
max = p->data;
}
p=p->next;
}
cout << "Max element : " << max << endl;
}
void min(node *p){
int min = p->data;
while(p){
if(p->data < min){
min = p->data;
}
p = p->next;
}
cout << "Min element : " << min << endl;
}
void search(node *p,int key){
int count=0;
while(p){
count++;
if(p -> data == key){
cout << "Found " << key << "! in node " << count << endl;
break;
}
p = p->next;
}
}
int rsearch(node *p,int key){
if(p==NULL){
return 0;
}
if(p->data == key){
return key;
}
return rsearch(p->next,key);
}
int main(){
int a[]={1,2,3,4,5,6,7,8,9,10};
insert(a,10);
display(start);
cout << "Recursive Count : " << rcount(start) << endl;
sum(start);
cout << "Recursive Sum : " << rsum(start) << endl;
max(start);
min(start);
search(start,4);
cout << "Recursive Search : " << rsearch(start,4) << " found!" << endl;
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment