1.
#include <stdio.h>
#include <stdlib.h> // Required for malloc, realloc, free
// Define a structure for the stack
typedef struct {
int *array; // Pointer to the dynamically allocated array
int capacity; // Maximum capacity of the stack
int top; // Index of the top element
} Stack;
// Function to create a new stack
// Initializes the stack with a given initial capacity
Stack* createStack(int initialCapacity) {
Stack* stack = (Stack*)malloc(sizeof(Stack)); // Allocate memory for the Stack structure
if (stack == NULL) {
printf("Memory allocation failed for stack structure!\n");
exit(EXIT_FAILURE);
stack->capacity = initialCapacity;
stack->top = -1; // Stack is initially empty
stack->array = (int*)malloc(stack->capacity * sizeof(int)); // Allocate memory for the array
if (stack->array == NULL) {
printf("Memory allocation failed for stack array!\n");
free(stack); // Free the stack structure if array allocation fails
exit(EXIT_FAILURE);
printf("Stack created with initial capacity %d.\n", initialCapacity);
return stack;
}
// Function to check if the stack is full
// Returns 1 if full, 0 otherwise
int isFull(Stack* stack) {
return stack->top == stack->capacity - 1;
// Function to check if the stack is empty
// Returns 1 if empty, 0 otherwise
int isEmpty(Stack* stack) {
return stack->top == -1;
// Function to resize the stack array
// Doubles the capacity when the stack is full
void resizeStack(Stack* stack) {
int newCapacity = stack->capacity * 2; // Double the capacity
stack->array = (int*)realloc(stack->array, newCapacity * sizeof(int)); // Reallocate memory
if (stack->array == NULL) {
printf("Memory reallocation failed during resize!\n");
exit(EXIT_FAILURE);
stack->capacity = newCapacity;
printf("Stack resized. New capacity: %d\n", newCapacity);
// Function to push an element onto the stack
void PUSH(Stack* stack, int item) {
if (isFull(stack)) {
printf("Stack is full. Resizing...\n");
resizeStack(stack); // Resize if full
}
stack->array[++stack->top] = item; // Increment top and add the item
printf("%d pushed to stack.\n", item);
// Function to pop an element from the stack
int POP(Stack* stack) {
if (isEmpty(stack)) {
printf("Stack Underflow! Cannot pop from an empty stack.\n");
return -1; // Indicate an error or invalid value
int item = stack->array[stack->top--]; // Get item and decrement top
printf("%d popped from stack.\n", item);
return item;
// Function to peek at the top element of the stack without removing it
int PEEK(Stack* stack) {
if (isEmpty(stack)) {
printf("Stack is empty. Cannot peek.\n");
return -1; // Indicate an error or invalid value
printf("Top element is: %d\n", stack->array[stack->top]);
return stack->array[stack->top];
// Function to display all elements in the stack
void DISPLAY(Stack* stack) {
if (isEmpty(stack)) {
printf("Stack is empty. Nothing to display.\n");
return;
}
printf("Stack elements (top to bottom):\n");
int i; // Declare 'i' outside the for loop
for (i = stack->top; i >= 0; i--) {
printf("| %d |\n", stack->array[i]);
printf("-----\n");
// Function to free the memory allocated for the stack
void freeStack(Stack* stack) {
if (stack != NULL) {
free(stack->array); // Free the array first
free(stack); // Then free the stack structure
printf("Stack memory freed.\n");
int main() {
Stack* myStack = createStack(5); // Create a stack with initial capacity 5
int choice, item;
do {
printf("\n--- Stack Operations Menu ---\n");
printf("1. PUSH\n");
printf("2. POP\n");
printf("3. PEEK\n");
printf("4. DISPLAY\n");
printf("0. Exit\n");
printf("Enter your choice: ");
scanf("%d", &choice);
switch (choice) {
case 1:
printf("Enter item to push: ");
scanf("%d", &item);
PUSH(myStack, item);
break;
case 2:
POP(myStack);
break;
case 3:
PEEK(myStack);
break;
case 4:
DISPLAY(myStack);
break;
case 0:
printf("Exiting program.\n");
break;
default:
printf("Invalid choice. Please try again.\n");
} while (choice != 0);
freeStack(myStack); // Free allocated memory before exiting
return 0;
2.
#include <stdio.h>
#include <stdlib.h>
typedef struct {
int *array;
int capacity;
int front;
int rear;
int size;
} Queue;
Queue* createQueue(int initialCapacity) {
Queue* q = (Queue*)malloc(sizeof(Queue));
q->capacity = initialCapacity;
q->front = 0;
q->rear = -1;
q->size = 0;
q->array = (int*)malloc(q->capacity * sizeof(int));
return q;
int isFull(Queue* q) {
return q->size == q->capacity;
int isEmpty(Queue* q) {
return q->size == 0;
void resizeQueue(Queue* q) {
q->capacity *= 2;
q->array = (int*)realloc(q->array, q->capacity * sizeof(int));
printf("Queue resized to %d\n", q->capacity);
}
void enqueue(Queue* q, int item) {
if (isFull(q)) resizeQueue(q);
q->rear = (q->rear + 1) % q->capacity;
q->array[q->rear] = item;
q->size++;
printf("%d enqueued.\n", item);
int dequeue(Queue* q) {
if (isEmpty(q)) {
printf("Queue is empty.\n");
return -1;
int item = q->array[q->front];
q->front = (q->front + 1) % q->capacity;
q->size--;
printf("%d dequeued.\n", item);
return item;
int peek(Queue* q) {
if (isEmpty(q)) {
printf("Queue is empty.\n");
return -1;
printf("Front element: %d\n", q->array[q->front]);
return q->array[q->front];
void displayQueue(Queue* q) {
if (isEmpty(q)) {
printf("Queue is empty.\n");
return;
printf("Queue elements: ");
for (int i = 0; i < q->size; i++) {
printf("%d ", q->array[(q->front + i) % q->capacity]);
printf("\n");
void freeQueue(Queue* q) {
free(q->array);
free(q);
int main() {
Queue* myQueue = createQueue(5);
int choice, item;
do {
printf("\n--- Queue Menu ---\n");
printf("1. Enqueue\n");
printf("2. Dequeue\n");
printf("3. Peek\n");
printf("4. Display\n");
printf("0. Exit\n");
printf("Enter choice: ");
scanf("%d", &choice);
switch(choice) {
case 1:
printf("Enter item: ");
scanf("%d", &item);
enqueue(myQueue, item);
break;
case 2:
dequeue(myQueue);
break;
case 3:
peek(myQueue);
break;
case 4:
displayQueue(myQueue);
break;
case 0:
printf("Exiting...\n");
break;
default:
printf("Invalid choice.\n");
} while (choice != 0);
freeQueue(myQueue);
return 0;
3. Reverse a String using Stack (ADT)
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct {
char *arr;
int top;
int capacity;
} Stack;
Stack* createStack(int capacity) {
Stack *stack = (Stack*)malloc(sizeof(Stack));
stack->capacity = capacity;
stack->top = -1;
stack->arr = (char*)malloc(capacity * sizeof(char));
return stack;
void push(Stack *stack, char ch) {
if (stack->top == stack->capacity - 1) return;
stack->arr[++stack->top] = ch;
char pop(Stack *stack) {
if (stack->top == -1) return '\0';
return stack->arr[stack->top--];
int main() {
char str[100];
int i;
printf("Enter a string: ");
gets(str); // For C90 compatibility
int len = strlen(str);
Stack *stack = createStack(len);
for (i = 0; i < len; i++)
push(stack, str[i]);
printf("Reversed string: ");
for (i = 0; i < len; i++)
printf("%c", pop(stack));
printf("\n");
free(stack->arr);
free(stack);
return 0;
4. Double Stack (Both Ends Operations)
#include <stdio.h>
#include <stdlib.h>
typedef struct {
int *arr;
int top1, top2;
int capacity;
} DoubleStack;
DoubleStack* createDoubleStack(int capacity) {
DoubleStack *ds = (DoubleStack*)malloc(sizeof(DoubleStack));
ds->capacity = capacity;
ds->top1 = -1;
ds->top2 = capacity;
ds->arr = (int*)malloc(capacity * sizeof(int));
return ds;
void push1(DoubleStack *ds, int val) {
if (ds->top1 + 1 == ds->top2) {
printf("Stack Overflow\n");
return;
ds->arr[++ds->top1] = val;
void push2(DoubleStack *ds, int val) {
if (ds->top1 + 1 == ds->top2) {
printf("Stack Overflow\n");
return;
ds->arr[--ds->top2] = val;
int pop1(DoubleStack *ds) {
if (ds->top1 == -1) {
printf("Stack Underflow\n");
return -1;
return ds->arr[ds->top1--];
int pop2(DoubleStack *ds) {
if (ds->top2 == ds->capacity) {
printf("Stack Underflow\n");
return -1;
return ds->arr[ds->top2++];
}
int main() {
int i;
DoubleStack *ds = createDoubleStack(10);
push1(ds, 1);
push1(ds, 2);
push2(ds, 9);
push2(ds, 8);
printf("Pop from Stack 1: %d\n", pop1(ds));
printf("Pop from Stack 2: %d\n", pop2(ds));
free(ds->arr);
free(ds);
return 0;
5. Palindrome Check (Ignoring Spaces, Case, Punctuation)
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
int is_palindrome(char *text) {
int len = strlen(text);
char *clean = (char*)malloc(len + 1);
int j = 0, i;
// Clean text: remove non-alphanumeric & lowercase
for (i = 0; i < len; i++) {
if (isalnum((unsigned char)text[i])) {
clean[j++] = tolower((unsigned char)text[i]);
}
clean[j] = '\0';
int left = 0, right = j - 1;
while (left < right) {
if (clean[left] != clean[right]) {
free(clean);
return 0;
left++;
right--;
free(clean);
return 1;
int main() {
char text[200];
printf("Enter text: ");
gets(text); // C90 safe input
if (is_palindrome(text))
printf("Palindrome\n");
else
printf("Not a palindrome\n");
return 0;
1. Queue Implementation Using Two Stacks
#include <stdio.h>
#include <stdlib.h>
#define MAX 100
typedef struct {
int arr[MAX];
int top;
} Stack;
void initStack(Stack *s) {
s->top = -1;
int isEmpty(Stack *s) {
return s->top == -1;
int isFull(Stack *s) {
return s->top == MAX - 1;
void push(Stack *s, int value) {
if (isFull(s)) {
printf("Stack overflow!\n");
return;
s->arr[++(s->top)] = value;
int pop(Stack *s) {
if (isEmpty(s)) {
printf("Stack underflow!\n");
return -1;
return s->arr[(s->top)--];
void enqueue(Stack *s1, int value) {
push(s1, value);
int dequeue(Stack *s1, Stack *s2) {
int val;
if (isEmpty(s1) && isEmpty(s2)) {
printf("Queue is empty!\n");
return -1;
if (isEmpty(s2)) {
while (!isEmpty(s1)) {
push(s2, pop(s1));
val = pop(s2);
return val;
int main() {
Stack s1, s2;
int choice, val;
initStack(&s1);
initStack(&s2);
while (1) {
printf("\nQueue using Stack Operations:\n");
printf("1. Enqueue\n2. Dequeue\n3. Exit\nEnter choice: ");
scanf("%d", &choice);
if (choice == 1) {
printf("Enter value: ");
scanf("%d", &val);
enqueue(&s1, val);
} else if (choice == 2) {
val = dequeue(&s1, &s2);
if (val != -1)
printf("Dequeued: %d\n", val);
} else if (choice == 3) {
break;
} else {
printf("Invalid choice!\n");
return 0;
2. Circular Queue Implementation
#include <stdio.h>
#include <stdlib.h>
#define MAX 5
typedef struct {
int arr[MAX];
int front;
int rear;
int count;
} CircularQueue;
void initQueue(CircularQueue *q) {
q->front = 0;
q->rear = -1;
q->count = 0;
int isFull(CircularQueue *q) {
return q->count == MAX;
int isEmpty(CircularQueue *q) {
return q->count == 0;
void enqueue(CircularQueue *q, int value) {
if (isFull(q)) {
printf("Queue is full!\n");
return;
q->rear = (q->rear + 1) % MAX;
q->arr[q->rear] = value;
q->count++;
int dequeue(CircularQueue *q) {
int val;
if (isEmpty(q)) {
printf("Queue is empty!\n");
return -1;
val = q->arr[q->front];
q->front = (q->front + 1) % MAX;
q->count--;
return val;
void display(CircularQueue *q) {
int i, idx;
if (isEmpty(q)) {
printf("Queue is empty!\n");
return;
printf("Queue elements: ");
idx = q->front;
for (i = 0; i < q->count; i++) {
printf("%d ", q->arr[idx]);
idx = (idx + 1) % MAX;
printf("\n");
int main() {
CircularQueue q;
int choice, val;
initQueue(&q);
while (1) {
printf("\nCircular Queue Operations:\n");
printf("1. Enqueue\n2. Dequeue\n3. Display\n4. Exit\nEnter choice: ");
scanf("%d", &choice);
if (choice == 1) {
printf("Enter value: ");
scanf("%d", &val);
enqueue(&q, val);
} else if (choice == 2) {
val = dequeue(&q);
if (val != -1)
printf("Dequeued: %d\n", val);
} else if (choice == 3) {
display(&q);
} else if (choice == 4) {
break;
} else {
printf("Invalid choice!\n");
return 0;
1. Python program to implement a Stack
class Stack:
def __init__(self):
self.stack = []
def push(self, item):
self.stack.append(item)
def pop(self):
if not self.is_empty():
return self.stack.pop()
else:
return None
def peek(self):
if not self.is_empty():
return self.stack[-1]
else:
return None
def is_empty(self):
return len(self.stack) == 0
def display(self):
print("Stack:", self.stack)
if __name__ == "__main__":
s = Stack()
while True:
print("\n1. Push\n2. Pop\n3. Peek\n4. Display\n5. Exit")
choice = int(input("Enter your choice: "))
if choice == 1:
val = input("Enter value to push: ")
s.push(val)
elif choice == 2:
popped = s.pop()
print("Popped:", popped if popped is not None else "Stack Empty")
elif choice == 3:
print("Top:", s.peek())
elif choice == 4:
s.display()
elif choice == 5:
break
else:
print("Invalid choice!")
2. Python program to implement a Queue
class Queue:
def __init__(self):
self.queue = []
def enqueue(self, item):
self.queue.append(item)
def dequeue(self):
if not self.is_empty():
return self.queue.pop(0)
else:
return None
def is_empty(self):
return len(self.queue) == 0
def display(self):
print("Queue:", self.queue)
if __name__ == "__main__":
q = Queue()
while True:
print("\n1. Enqueue\n2. Dequeue\n3. Display\n4. Exit")
choice = int(input("Enter your choice: "))
if choice == 1:
val = input("Enter value to enqueue: ")
q.enqueue(val)
elif choice == 2:
removed = q.dequeue()
print("Dequeued:", removed if removed is not None else "Queue Empty")
elif choice == 3:
q.display()
elif choice == 4:
break
else:
print("Invalid choice!")
3. Reverse a string using Stack (Array)
def reverse_string(s):
stack = list(s) # Push all characters
reversed_str = ""
while stack:
reversed_str += stack.pop()
return reversed_str
if __name__ == "__main__":
text = input("Enter a string: ")
print("Reversed string:", reverse_string(text))
4. Circular Queue using Array
class CircularQueue:
def __init__(self, size):
self.size = size
self.queue = [None] * size
self.front = -1
self.rear = -1
def enqueue(self, data):
if (self.rear + 1) % self.size == self.front:
print("Queue is Full")
elif self.front == -1:
self.front = self.rear = 0
self.queue[self.rear] = data
else:
self.rear = (self.rear + 1) % self.size
self.queue[self.rear] = data
def dequeue(self):
if self.front == -1:
print("Queue is Empty")
elif self.front == self.rear:
temp = self.queue[self.front]
self.front = self.rear = -1
return temp
else:
temp = self.queue[self.front]
self.front = (self.front + 1) % self.size
return temp
def display(self):
if self.front == -1:
print("Queue is Empty")
else:
i = self.front
while True:
print(self.queue[i], end=" ")
if i == self.rear:
break
i = (i + 1) % self.size
print()
if __name__ == "__main__":
size = int(input("Enter the size of Circular Queue: "))
cq = CircularQueue(size)
while True:
print("\n1. Enqueue\n2. Dequeue\n3. Display\n4. Exit")
choice = int(input("Enter your choice: "))
if choice == 1:
val = input("Enter value: ")
cq.enqueue(val)
elif choice == 2:
print("Dequeued:", cq.dequeue())
elif choice == 3:
cq.display()
elif choice == 4:
break
5. Remove Non-Primary Color Boxes from Stack
class Stack:
def __init__(self):
self.stack = []
def push(self, item):
self.stack.append(item)
def pop(self):
if not self.is_empty():
return self.stack.pop()
else:
return None
def is_empty(self):
return len(self.stack) == 0
def display(self):
print("Stack:", self.stack)
class Queue:
def __init__(self, size):
self.queue = []
self.size = size
def enqueue(self, item):
if len(self.queue) < self.size:
self.queue.append(item)
else:
print("Queue is Full")
def display(self):
print("Queue:", self.queue)
def filter_primary_colors(stack):
primary_colors = {"Red", "Green", "Blue"}
removed_queue = Queue(len(stack.stack))
temp_stack = []
while not stack.is_empty():
box = stack.pop()
if box in primary_colors:
temp_stack.append(box)
else:
removed_queue.enqueue(box)
while temp_stack:
stack.push(temp_stack.pop())
return removed_queue
if __name__ == "__main__":
s = Stack()
n = int(input("Enter number of boxes: "))
for _ in range(n):
s.push(input("Enter box color: "))
removed = filter_primary_colors(s)
print("\nFiltered Stack (Primary colors only):")
s.display()
print("Removed Boxes (Non-primary colors):")
removed.display()