tt
🧩 Syntax:
#include <stdio.h>
#include <stdlib.h>
// Node structure
struct Node {
int data;
struct Node* next;
};
struct Node* top = NULL; // top of stack
// Push function
void push(int x) {
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
if (!newNode) {
printf("Stack Overflow\n");
return;
}
newNode->data = x;
newNode->next = top;
top = newNode;
printf("%d pushed to stack\n", x);
}
// Pop function
void pop() {
if (top == NULL) {
printf("Stack Underflow\n");
return;
}
struct Node* temp = top;
printf("%d popped from stack\n", top->data);
top = top->next;
free(temp);
}
// Peek function
void peek() {
if (top == NULL) {
printf("Stack is empty\n");
return;
}
printf("Top element is %d\n", top->data);
}
// Display stack
void display() {
struct Node* temp = top;
if (temp == NULL) {
printf("Stack is empty\n");
return;
}
printf("Stack elements: ");
while (temp != NULL) {
printf("%d ", temp->data);
temp = temp->next;
}
printf("\n");
}
int main() {
push(11);
push(20);
push(30);
display();
peek();
pop();
display();
peek();
return 0;
}