Files
2025-12-08 23:41:37 +05:30

102 lines
1.8 KiB
C

#include <stdio.h>
#include <stdlib.h>
// Node structure
typedef struct node {
int data;
struct node *next;
} NODE;
NODE *top = NULL;
// Push operation
void push(int value) {
NODE *newNode = (NODE*)malloc(sizeof(NODE));
if (!newNode) {
printf("Memory allocation failed!\n");
return;
}
newNode->data = value;
newNode->next = top;
top = newNode;
printf("Pushed %d onto stack\n", value);
}
// Pop operation
int pop() {
NODE *temp;
int value;
if (top == NULL) {
printf("Stack Underflow! Stack is empty.\n");
return -1;
}
temp = top;
value = temp->data;
top = top->next;
free(temp);
return value;
}
// Display stack contents
void display() {
NODE *temp = top;
if (top == NULL) {
printf("Stack is empty.\n");
return;
}
printf("Stack contents:\n");
while (temp != NULL) {
printf("%d -> ", temp->data);
temp = temp->next;
}
printf("NULL\n");
}
// Main menu
int main() {
int choice, value;
while (1) {
printf("\n--- STACK MENU ---\n");
printf("1. Push\n");
printf("2. Pop\n");
printf("3. Display\n");
printf("4. Exit\n");
printf("Enter choice: ");
scanf("%d", &choice);
switch (choice) {
case 1:
printf("Enter value to push: ");
scanf("%d", &value);
push(value);
break;
case 2:
value = pop();
if (value != -1)
printf("Popped value: %d\n", value);
break;
case 3:
display();
break;
case 4:
printf("Exiting...\n");
exit(0);
default:
printf("Invalid choice. Try again.\n");
}
}
}