Expp
Expp
Source Code:
#include <stdio.h>
#define MAX 5
int stack[MAX], top = -1;
void push(int value) {
if (top == MAX - 1) {
printf("Stack Overflow! Cannot push %d\n", value);
} else {
stack[++top] = value;
printf("%d pushed into the stack.\n", value);
}
}
int pop() {
if (top == -1) {
printf("Stack Underflow! No elements to pop.\n");
return -1;
} else {
printf("%d popped from the stack.\n", stack[top]);
return stack[top--];
}
}
int peek() {
if (top == -1) {
printf("Stack is empty! No top element.\n");
return -1;
} else {
printf("Top element is: %d\n", stack[top]);
return stack[top];
}
}
void display() {
if (top == -1) {
printf("Stack is empty.\n");
} else {
printf("Stack elements: ");
for (int i = top; i >= 0; i--) {
printf("%d ", stack[i]);
}
printf("\n");
Experiment No: 4
Source Code:
#include <stdio.h>
#include <stdlib.h>
struct Node {
int data;
struct Node* next;
};
int main() {
struct Node* top = NULL;
int choice, value;
while (1) {
printf("\nStack Operations:\n");
printf("1. Push\n");
printf("2. Pop\n");
printf("3. Display\n");
printf("4. Exit\n");
printf("Enter your choice: ");
scanf("%d", &choice);
switch (choice) {
case 1:
printf("Enter value to push: ");
scanf("%d", &value);
push(&top, value);
break;
case 2:
pop(&top);
break;
case 3:
display(top);
break;
case 4:
printf("Exiting...\n");
while (top) pop(&top);
return 0;
default:
printf("Invalid choice, please try again.\n");
}
}
return 0;
}
Output: