Recursion Stack Queue.docx
Recursion Stack Queue.docx
1. Factorial
2. Fibonacci
3. Sum of 10 numbers
4. Tower of hanoi
#include <iostream>
using namespace std;
void tower(int n, char beg, char end, char aux) {
if(n == 1){
cout<<beg<<" -> "<<end<<endl;
}
else{
tower(n-1, beg, aux, end);
cout<<beg<<" -> "<<end<<endl;
tower(n-1, aux, end, beg);
}
}
int main() {
int n = 4;
char beg = 'A';
char end = 'B';
char aux = 'C';
tower(n, beg , aux, end);
}
Stack:
#include <bits/stdc++.h>
using namespace std;
int MAX_SIZE=50;
int top = -1;
int main() {
int stack[MAX_SIZE];
push(stack,10);
push(stack,20);
push(stack,30);
printStack(stack);
pop(stack);
printStack(stack);
return 0;
}
#include <bits/stdc++.h>
using namespace std;
void display(stack<int>St) {
if (St.empty()) {
cout<<"Stack is empty.";
} else {
cout<<"Stack elements: ";
while(!St.empty()){
cout << ' '<< St.top();
St.pop();
}
cout<<endl;
}
}
int main() {
stack <int> St;
St.push(10);
St.push(20);
St.push(30);
display(St);
St.pop();
display(St);
return 0;
}
#include<bits/stdc++.h>
using namespace std;
int evaluatePostfix(string expression) {
stack<int>st;
for (int i=0; i<expression.length();i++) {
if(isdigit(expression[i])) {
st.push(expression[i]-'0'); //Convert char to int
}
else {
// Operator encountered
int A = st.top();
st.pop();
int B = st.top();
st.pop();
switch (expression[i]) {
case '+':
st.push(B + A);
break;
case '-':
st.push(B - A);
break;
case '*':
st.push(B * A);
break;
case '/':
st.push(B / A);
break;
default:
cout<<"Invalid operator: "<< endl;
}
}
}
return st.top();
}
int main() {
string postfix = "562+*94/-";
cout<<"Result : "<<evaluatePostfix(postfix);
return 0;
}
QUEUE:
#include <bits/stdc++.h>
#define MAX_SIZE 6
using namespace std;
int front = -1, rear = -1;
int main() {
int queue[MAX_SIZE];
insertion(queue,10);
insertion(queue,20);
insertion(queue,30);
insertion(queue,40);
insertion(queue,50);
insertion(queue,60);
display(queue);
deletion(queue);
deletion(queue);
deletion(queue);
display(queue);
insertion(queue,77);
insertion(queue,88);
display(queue);
return 0;
}
#include <bits/stdc++.h>
using namespace std;
void display(queue<int>q) {
if (q.empty()) {
cout<<"Queue is empty.";
} else {
cout<<"Queue elements: ";
while(!q.empty()){
cout << ' '<< q.front();
q.pop();
}
cout<<endl;
}
}
int main() {
queue<int>q;
q.push(10);
q.push(20);
q.push(30);
display(q);
q.pop();
display(q);
return 0;
}