A stack is a LiFo (Last-in, first-out) data structure with three basic operation
ID: 3663668 • Letter: A
Question
A stack is a LiFo (Last-in, first-out) data structure with three basic operations: push, pop and peek, push is putting an element, on the top of the stack, pop removes (and returns) the top element, and peek returns (without removing) the top element. Think of a stack as a pile of plates that can be found in certain restaurants. You can only add and remove the top-most plate. You can not remove any plates in the middle of the pile (without first removing all plates above it). Your task is to write a Java class Stack, java that implements the following interface: Notice: You are not allowed to use any of the classes in the Java Library. However, you can use arrays.Explanation / Answer
import java.util.NoSuchElementException;
public class Stack implements IntStack
{
private int[] array;
private int size = 0; // Initial size of the stack is zero
public Stack(int capacity) { // Constructor --> Initializes a stack of size equal to capacity
array = new int[capacity];
}
public int size() {
return size;
}
public boolean isEmpty() {
return size == 0;
}
public void push(int element) {
if (size == array.length) {
throw new IllegalStateException("Cannot add to full stack");
}
else
array[size++] = element;
}
public int pop() {
if (size == 0) {
throw new NoSuchElementException("Cannot pop from empty stack");
}
else{
int result = array[size-1];
size--;
return result;
}
}
public int peek() {
if (size == 0) {
throw new NoSuchElementException("Cannot peek into empty stack");
}
return array[size - 1];
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.