Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Recursion codes #345

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions Recursion/Code
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@

29 changes: 29 additions & 0 deletions Recursion/TowerOfHanoi.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
#include<bits/stdc++.h>
using namespace std;

void towerOfHanoi(int s,int h, int d, int n)
{
if(n==1)
{
cout << "move disk " << n << " from rod " << s << " to rod " << d << "\n";
return;
}
towerOfHanoi(s,d,h,n-1);
cout << "move disk " << n << " from rod " << s << " to rod " << d << "\n";
towerOfHanoi(h,s,d,n);
return;
}

int main()
{
int t;
cin >> t;
while(t--)
{
int n;
cin >> n;
int s = 1, h = 2, d = 3;
towerOfHanoi(s,h,d,n);
}
return 0;
}
48 changes: 48 additions & 0 deletions Recursion/reverseStack.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@

#include<bits/stdc++.h>
using namespace std;
void insertTemp(stack<int>&s,int temp)
{
if(s.size()==0)
{
s.push(temp);
return;
}
int val = s.top();
s.pop();
insertTemp(s,temp);
s.push(val);
return;

}
void reverseStack(stack<int>&s)
{
if(s.size()==1)
return;
int temp = s.top();
s.pop();
reverseStack(s);
insertTemp(s,temp);
}


int main()
{
stack<int>s;
int n;
cin >> n;
for(int i=0; i<n; i++)
{
int x;
cin >> x;
s.push(x);
}
reverseStack(s);
for(int i=0; i<n; i++)
{
cout << s.top() << " ";
s.pop();
}
return 0;
}

47 changes: 47 additions & 0 deletions Recursion/stackSort.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@

#include<bits/stdc++.h>
using namespace std;
void insertTemp(stack<int>&s,int temp)
{
if(s.size()==0 || s.top()<=temp)
{
s.push(temp);
return;
}
int val = s.top();
s.pop();
insertTemp(s,temp);
s.push(val);
return;

}
void sortStack(stack<int>&s)
{
if(s.size()==1)
return;
int temp = s.top();
s.pop();
sortStack(s);
insertTemp(s,temp);
}


int main()
{
stack<int>s;
int n;
cin >> n;
for(int i=0; i<n; i++)
{
int x;
cin >> x;
s.push(x);
}
sortStack(s);
for(int i=0; i<n; i++)
{
cout << s.top() << " ";
s.pop();
}
return 0;
}