public interface Stack {
void push(int element);
int pop();
int peek();
boolean isEmpty();
boolean isFull();
}
//
public class FixedSizeStack implements Stack {
private int[] stackData;
private int top;
public FixedSizeStack(int n) {
stackData = new int[n];
top = -1;
}
@Override
public void push(int element) {
if (isFull()) {
throw new IllegalStateException("Stack is full. Cannot push element.");
}
stackData[++top] = element;
}
@Override
public int pop() {
if (isEmpty()) {
throw new IllegalStateException("Stack is empty. Cannot pop element.");
}
return stackData[top--];
}
@Override
public int peek() {
if (isEmpty()) {
throw new IllegalStateException("Stack is empty. Cannot peek
element.");
}
return stackData[top];
}
@Override
public boolean isEmpty() {
return top == -1;
}
@Override
public boolean isFull() {
return top == ([Link] - 1);
}
}
//
public class StackTest {
public static void main(String[] args) {
FixedSizeStack stack = new FixedSizeStack(5);
// Pushing elements onto the stack
[Link](10);
[Link](20);
[Link](30);
[Link](40);
[Link](50);
// Peek the top element
[Link]("Top element: " + [Link]());
// Try pushing onto a full stack (won't be added)
[Link](60); // Stack is full, so this will not be added
// Popping elements from the stack
[Link]("Popped element: " + [Link]());
[Link]("Popped element: " + [Link]());
[Link]("Popped element: " + [Link]());
[Link]("Popped element: " + [Link]());
[Link]("Popped element: " + [Link]());
// Check if stack is empty
[Link]("Is stack empty? " + [Link]());
}
}