#include <stdio.
h>
#include <stdlib.h>
// Define the structure for a node in the linked list
struct Node {
int data;
struct Node* next;
};
// Global pointer to the top of the stack
struct Node* top = NULL;
void push(int data) {
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
if (newNode == NULL) {
printf("Stack is full. Cannot push element.\n");
return;
}
newNode->data = data;
newNode->next = top;
top = newNode;
printf("Pushed element: %d\n", data);
}
// Function to pop the top element from the stack
void pop() {
if (top == NULL) {
printf("Stack is empty. Cannot pop element.\n");
return;
}
struct Node* temp = top;
top = top->next;
int data = temp->data;
free(temp);
printf("Popped element: %d\n", data);
}
void peek() {
if (top == NULL) {
printf("Stack is empty.\n");
return;
}
printf("Top element: %d\n", top->data);
}
int isEmpty() {
return top == NULL;
}
int isFull() {
return 0; // Linked list-based stack is never full
}
void display() {
struct Node* current = top;
if (current == NULL) {
printf("Stack is empty.\n");
} else {
printf("Stack: ");
while (current != NULL) {
printf("%d -> ", current->data);
current = current->next;
}
printf("NULL\n");
}}
int main() {
int choice, data;
while (1) {
printf("\nMenu:\n");
printf("1. Push\n");
printf("2. Pop\n");
printf("3. Peek\n");
printf("4. IsEmpty\n");
printf("5. IsFull\n");
printf("6. Display\n");
printf("7. Exit\n");
printf("Enter your choice: ");
scanf("%d", &choice);
switch (choice) {
case 1:
printf("Enter data to push: ");
scanf("%d", &data);
push(data);
break;
case 2:
pop();
break;
case 3:
peek();
break;
case 4:
if (isEmpty()) {
printf("Stack is empty.\n");
} else {
printf("Stack is not empty.\n");
}
break;
case 5:
if (isFull()) {
printf("Stack is full.\n");
} else {
printf("Stack is not full.\n"); }
break;
case 6:
display();
break;
case 7:
exit(0);
default:
printf("Invalid choice. Please try again.\n");
}
return 0;
}