Intern — Middle
Basic stack implementation
livecode
Task condition
It is necessary to implement a simple stack supporting basic operations: adding an element, removing the top element, viewing the top without removing, and checking the stack's state (empty/full). A class Stack should be created with methods push(), pop(), peek(), isEmpty(), and isFull(). In the main() function, a fixed-size stack is created, several values are added to it, and when trying to add an element to a full stack, an exception is handled. Then, the correctness of the peek and pop methods is checked by outputting the comparison results.
public class HelloWorld {
public static void main(String[] args) {
Stack myStack = new Stack(2);
myStack.push(1);
myStack.push(2);
try {
myStack.push(3);
} catch (Exception e) {
}
System.out.println(myStack.peek() == 2);
System.out.println(myStack.pop() == 2);
System.out.println(myStack.peek() == 1);
System.out.println(myStack.pop() == 1);
System.out.println(myStack.pop() == null);
}
static class Stack {
public Stack(int size) {
}
void push(int element) {
}
Integer peek() {
return -1;
}
Integer pop() {
return -1;
}
boolean isEmpty() {
return false;
}
boolean isFull() {
return false;
}
}
}