Member-only story
Top 5 Stack Interview Questions in Java
2 min readDec 18, 2023
Exercise 1: Implementing a Basic Stack
Objective: Implement a basic stack with push
, pop
, and peek
methods.
public class BasicStack {
private Node top;
public BasicStack() {
this.top = null;
}
public void push(int data) {
Node node = new Node(data);
node.next = top;
top = node;
}
public int pop() {
if (top == null) throw new IllegalStateException("Stack is empty");
int data = top.data;
top = top.next;
return data;
}
public int peek() {
if (top == null) throw new IllegalStateException("Stack is empty");
return top.data;
}
private static class Node {
int data;
Node next;
Node(int data) {
this.data = data;
}
}
}
Exercise 2: Checking Balanced Parentheses
Objective: Write a method to determine if a string of parentheses is balanced using a stack.
public boolean isBalanced(String s) {
Stack<Character> stack = new Stack<>();
for (char c : s.toCharArray()) {
if (c == '(') {
stack.push(c);
} else if (c == ')') {
if (stack.isEmpty()) {
return false;
}
stack.pop();
}…