#include <stdio.
h>
#include <stdlib.h>
struct Node {
int data;
struct Node* next;
};
struct Stack {
struct Node* head;
};
void createStack(struct Stack* stack);
void push(struct Stack* stack, int value);
void pop(struct Stack* stack);
void display(const struct Stack* stack);
void freeStack(struct Stack* stack);
int main() {
struct Stack stack;
int choice, value;
do {
printf("1. Create Stack\n");
printf("2. Push\n");
printf("3. Pop\n");
printf("4. Display\n");
printf("5. Exit\n");
printf("Enter your choice: ");
scanf("%d", &choice);
switch (choice) {
case 1:
createStack(&stack);
break;
case 2:
if (stack.head == NULL) {
printf("Please create the stack first.\n");
} else {
printf("Enter the value to push: ");
scanf("%d", &value);
push(&stack, value);
}
break;
case 3:
if (stack.head == NULL) {
printf("Stack is empty\n");
} else {
pop(&stack);
}
break;
case 4:
display(&stack);
break;
case 5:
freeStack(&stack);
break;
default:
printf("Invalid choice.\n");
}
} while (choice != 5);
return 0;
}
void createStack(struct Stack* stack) {
stack->head = NULL;
printf("Stack created successfully.\n");
}
void push(struct Stack* stack, int value) {
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
if (newNode == NULL) {
printf("Memory allocation failed\n");
return;
}
newNode->data = value;
newNode->next = stack->head;
stack->head = newNode;
printf("%d", value);
}
void pop(struct Stack* stack) {
struct Node* temp = stack->head;
stack->head = stack->head->next;
int poppedValue = temp->data;
free(temp);
printf("%d", poppedValue);
}
void display(const struct Stack* stack) {
if (stack->head == NULL) {
printf("Stack is empty.\n");
return;
}
struct Node* current = stack->head;
while (current != NULL) {
printf("%d ", current->data);
current = current->next;
}
printf("\n");
}
void freeStack(struct Stack* stack) {
struct Node* temp;
while (stack->head != NULL) {
temp = stack->head;
stack->head = stack->head->next;
free(temp);
}
}