🔴 Advanced · Lesson 39
Stack using C
Stack
Stack
A stack is a linear data structure that follows LIFO: Last In, First Out. The last inserted element is removed first.
| Operation | Meaning |
|---|---|
| Push | Insert element at top |
| Pop | Remove top element |
| Peek | View top element |
| isEmpty | Check whether stack is empty |
| isFull | Check overflow condition |
Overflow and Underflow
⚠️ Stack Conditions
- Overflow: pushing when stack is full
- Underflow: popping when stack is empty
Array Implementation
C Language
#include <stdio.h>
#define SIZE 5
int stack[SIZE], top = -1;
void push(int value) {
if(top == SIZE - 1) {
printf("Stack Overflow\n");
return;
}
stack[++top] = value;
}
int pop() {
if(top == -1) {
printf("Stack Underflow\n");
return -1;
}
return stack[top--];
}
int peek() {
if(top == -1) return -1;
return stack[top];
}
int main() {
push(10); push(20); push(30);
printf("Top = %d\n", peek());
printf("Popped = %d\n", pop());
printf("Top = %d", peek());
return 0;
}Top = 30
Popped = 30
Top = 20
Summary
- Stack follows LIFO order
- Top variable tracks the last inserted element
- Push inserts at top
- Pop removes from top
- Used in recursion, expression evaluation and undo operations
Stack
Stack एक linear data structure है जो LIFO follow करता है: Last In, First Out.
Operations
| Operation | Meaning |
|---|---|
| Push | Top पर insert |
| Pop | Top से remove |
| Peek | Top value देखना |
| Overflow | Stack full होने पर push |
| Underflow | Empty stack से pop |
Array Implementation
C Language
#define SIZE 5
int stack[SIZE], top = -1;
void push(int value) {
if(top == SIZE - 1) printf("Overflow");
else stack[++top] = value;
}
int pop() {
if(top == -1) return -1;
return stack[top--];
}सारांश
- Stack LIFO follow करता है
- top last inserted element को track करता है
- Push insert करता है
- Pop remove करता है
- Recursion और undo जैसी operations में use होता है