Q1. Implement a stack using an array
Solution and explanation
Solution
A stack follows LIFO (Last In, First Out). push() inserts, pop() removes the top element, and peek() returns the top without removing it.
Step by step
- Keep an array
stack[MAX]and an indextop, starting at-1(empty stack). - push(x): if
top == MAX - 1the stack is full (overflow); otherwise incrementtopand storexatstack[top]. - pop(): if
top == -1the stack is empty (underflow); otherwise returnstack[top]and decrementtop. - peek(): return
stack[top]without changingtop(or -1 when empty).
Dry run
| Operation | top after | Stack (bottom → top) | Returns |
|---|---|---|---|
| push(10) | 0 | 10 | — |
| push(20) | 1 | 10, 20 | — |
| pop() | 0 | 10 | 20 |
| peek() | 0 | 10 | 10 |
C
#include <stdio.h>
#define MAX 100
int stack[MAX], top = -1;
void push(int x) {
if (top == MAX - 1) {
printf("Stack Overflow\n");
return;
}
stack[++top] = x;
}
int pop(void) {
if (top == -1) {
printf("Stack Underflow\n");
return -1;
}
return stack[top--];
}
int peek(void) {
return top == -1 ? -1 : stack[top];
}
int main(void) {
push(10);
push(20);
printf("%d\n", pop()); // 20
printf("%d\n", peek()); // 10
return 0;
}
C++
#include <iostream>
#include <stack>
using namespace std;
int main() {
stack<int> s;
s.push(10);
s.push(20);
cout << s.top() << '\n'; // 20
s.pop();
cout << s.top() << '\n'; // 10
}
Java
import java.util.ArrayDeque;
import java.util.Deque;
public class Main {
public static void main(String[] args) {
Deque<Integer> stack = new ArrayDeque<>();
stack.push(10);
stack.push(20);
System.out.println(stack.peek()); // 20
System.out.println(stack.pop()); // 20
}
}
Complexity
- push, pop and peek: O(1) time each.
- Space: O(n) for the array.
Note: in Java prefer ArrayDeque over the legacy Stack class, which is synchronized and therefore slower.
