#include <stdio.h>
#include <stdlib.h>
struct node {
int data;
struct node* next;
};
struct node* top = NULL;
// Push
void push(int x) {
struct node* newnode = (struct node*)malloc(sizeof(struct node));
if (newnode == NULL) {
printf("Overflow\n");
return;
}
newnode->data = x;
newnode->next = top;
top = newnode;
printf("Pushed %d\n", x);
}
// Pop
void pop() {
if (top == NULL) {
printf("Underflow\n");
return;
}
struct node* temp = top;
printf("Popped %d\n", temp->data);
top = top->next;
free(temp);
}
// Display
void display() {
struct node* temp = top;
if (temp == NULL) {
printf("Stack is empty\n");
return;
}
printf("Stack: ");
while (temp != NULL) {
printf("%d -> ", temp->data);
temp = temp->next;
}
printf("NULL\n");
}
// Main
int main() {
int ch, x;
do {
printf("\n--- STACK MENU ---\n");
printf("1.Push\n2.Pop\n3.Display\n4.Exit\n");
printf("Enter choice: ");
scanf("%d", &ch);
switch (ch) {
case 1:
printf("Enter value: ");
scanf("%d", &x);
push(x);
break;
case 2:
pop();
break;
case 3:
display();
break;
case 4:
printf("Exiting...\n");
break;
default:
printf("Invalid choice!\n");
}
} while (ch != 4);
return 0;
}
Preview:
downloadDownload PNG
downloadDownload JPEG
downloadDownload SVG
Tip: You can change the style, width & colours of the snippet with the inspect tool before clicking Download!
Click to optimize width for Twitter