import java.util.Stack;
public class MyStack {
private Stack<Integer> stack;
public MyStack() {
this.stack = new Stack<>();
}
public void push(int item) {
stack.push(item);
}
public int pop() {
return stack.pop();
}
public int peek() {
return stack.peek();
}
public boolean isEmpty() {
return stack.isEmpty();
}
public int size() {
return stack.size();
}
public static void main(String[] args) {
MyStack stack = new MyStack();
System.out.println("Is stack empty? " + stack.isEmpty());
stack.push(5);
stack.push(10);
stack.push(15);
System.out.println("Is stack empty? " + stack.isEmpty());
System.out.println("Size of stack: " + stack.size());
System.out.println("Top element of stack: " + stack.peek());
System.out.println("Popped element: " + stack.pop());
System.out.println("Size of stack after pop: " + stack.size());
}
}
java复制成功复制代码
This Java program creates a custom stack class MyStack that provides the functionalities of push, pop, peek, isEmpty, and size. The isEmpty() method returns true if the stack is empty and false if it contains elements. The peek() method returns the top element of the stack without removing it. The size() method returns the number of elements in the stack.
When running the main method, it demonstrates how to use these methods and shows the output based on the operations performed on the stack.