Answer:
1. Finding the Minimum Element in a Stack:
#include <stdio.h>
#include <stdlib.h>
#define MAX_SIZE 100
// Structure to represent a stack
struct Stack {
int items[MAX_SIZE];
int top;
};
// Initialize an empty stack
void init(struct Stack* stack) {
stack->top = -1;
}
// Check if the stack is empty
int isEmpty(struct Stack* stack) {
return stack->top == -1;
}
// Push an element onto the stack
void push(struct Stack* stack, int item) {
if (stack->top < MAX_SIZE - 1) {
stack->items[++stack->top] = item;
}
}
// Pop an element from the stack
int pop(struct Stack* stack) {
if (!isEmpty(stack)) {
return stack->items[stack->top--];
}
return -1; // Stack underflow
}
// Find the minimum element in the stack
int findMin(struct Stack* stack) {
int min = stack->items[stack->top];
for (int i = stack->top - 1; i >= 0; i--) {
if (stack->items[i] < min) {
min = stack->items[i];
}
}
return min;
}
int main() {
struct Stack stack;
init(&stack);
// Push elements onto the stack
push(&stack, 10);
push(&stack, 5);
push(&stack, 20);
push(&stack, 2);
push(&stack, 15);
int minimum = findMin(&stack);
printf("The minimum element in the stack is: %d\\", minimum);
return 0;
}
2. Reversing a Stack using Stack Operations:
#include <stdio.h>
#include <stdlib.h>
#define MAX_SIZE 100
// Structure to represent a stack
struct Stack {
int items[MAX_SIZE];
int top;
};
// Initialize an empty stack
void init(struct Stack* stack) {
stack->top = -1;
}
// Check if the stack is empty
int isEmpty(struct Stack* stack) {
return stack->top == -1;
}
// Push an element onto the stack
void push(struct Stack* stack, int item) {
if (stack->top < MAX_SIZE - 1) {
stack->items[++stack->top] = item;
}
}
// Pop an element from the stack
int pop(struct Stack* stack) {
if (!isEmpty(stack)) {
return stack->items[stack->top--];
}
return -1; // Stack underflow
}
// Function to reverse a stack
void reverseStack(struct Stack* source, struct Stack* target) {
while (!isEmpty(source)) {
int item = pop(source);
push(target, item);
}
}
// Function to display the stack
void display(struct Stack* stack) {
for (int i = 0; i <= stack->top; i++) {
printf("%d ", stack->items[i]);
}
printf("\\");
}
int main() {
struct Stack originalStack;
struct Stack reversedStack;
init(&originalStack);
init(&reversedStack);
// Push elements onto the original stack
push(&originalStack, 1);
push(&originalStack, 2);
push(&originalStack, 3);
push(&originalStack, 4);
push(&originalStack, 5);
printf("Original Stack: ");
display(&originalStack);
reverseStack(&originalStack, &reversedStack);
printf("Reversed Stack: ");
display(&reversedStack);
return 0;
}
Step-by-step explanation: