Assignment4
Assignment4
Problem Statement:
The Tower of Hanoi is a mathematical puzzle consisting of three rods and n disks of different sizes,
which
can slide onto any rod. The puzzle starts with all the disks stacked in ascending order of size on the
first rod. The objective of the puzzle is to move the entire stack to the third rod, obeying the following
rules:
2. Each move consists of taking the upper disk from one stack and placing it on top of another stack.
Approach:
1. Move the top n-1 disks from the source rod to the auxiliary rod.
2. Move the nth disk from the source rod to the target rod.
3. Move the n-1 disks from the auxiliary rod to the target rod.
Code Implementation:
#include <iostream>
if (n == 1) {
cout << "Move disk 1 from " << source << " to " << target << endl;
return;
cout << "Move disk " << n << " from " << source << " to " << target << endl;
int main() {
return 0;
Sample Input:
n=3
Sample Output:
Problem Statement:
Implement a first-in, first-out (FIFO) queue using only two stacks. The implemented queue should
2. pop(): Remove the element from the front of the queue and return it.
Approach:
3. For pop() and peek(), transfer elements from inputStack to outputStack if outputStack is empty,
Code Implementation:
#include <stack>
void transfer() {
while (!inputStack.empty()) {
outputStack.push(inputStack.top());
inputStack.pop();
public:
void push(int x) {
inputStack.push(x);
int pop() {
if (outputStack.empty()) transfer();
outputStack.pop();
return topElement;
int peek() {
if (outputStack.empty()) transfer();
return outputStack.top();
}
bool empty() {
};
Sample Input:
MyQueue q;
q.push(1);
q.push(2);
q.peek(); // returns 1
q.pop(); // returns 1
Sample Output:
false