How to create and use a stack in Java?
In Java, you can use the Stack class to create and use a stack. Here is an example code demonstrating how to create and use a stack:
import java.util.Stack;
public class StackExample {
public static void main(String[] args) {
// 创建一个栈对象
Stack<Integer> stack = new Stack<>();
// 将元素入栈
stack.push(1);
stack.push(2);
stack.push(3);
// 判断栈是否为空
System.out.println("栈是否为空:" + stack.isEmpty());
// 获取栈顶元素
System.out.println("栈顶元素:" + stack.peek());
// 出栈,打印并移除栈顶元素
while (!stack.isEmpty()) {
System.out.println("出栈元素:" + stack.pop());
}
}
}
The output result is:
栈是否为空:false
栈顶元素:3
出栈元素:3
出栈元素:2
出栈元素:1
In the code above, a Stack object is created first, and elements are pushed onto the stack using the push method. Then the isEmpty method is used to check if the stack is empty, the peek method is used to access the top element of the stack, and the pop method is used to remove and print the top element of the stack. Finally, all elements in the stack are popped out through a loop operation.