栈(Deque):
import java.util.ArrayDeque;
import java.util.Deque;
public class MyStack {
private Deque<Integer> stack;
public MyStack() {
stack = new ArrayDeque<>();
}
public boolean isEmpty() {
return stack.isEmpty();
}
public int size() {
return stack.size();
}
public void push(int item) {
stack.push(item);
}
public int pop() {
if (isEmpty()) {
throw new RuntimeException("栈为空。");
}
return stack.pop();
}
public int peek() {
if (isEmpty()) {
throw new RuntimeException("栈为空。");
}
return stack.peek();
}
public static void main(String[] args) {
MyStack myStack = new MyStack();
myStack.push(10);
myStack.push(20);
myStack.push(30);
System.out.println("栈大小: " + myStack.size());
System.out.println("栈顶元素: " + myStack.peek());
System.out.println("出栈元素: " + myStack.pop());
System.out.println("栈大小: " + myStack.size());
}
}
堆(Queue)
import java.util.LinkedList;
import java.util.Queue;
public class MyQueue {
private Queue<Integer> queue;
public MyQueue() {
queue = new LinkedList<>();
}
public boolean isEmpty() {
return queue.isEmpty();
}
public int size() {
return queue.size();
}
public void enqueue(int item) {
queue.add(item);
}
public int dequeue() {
if (isEmpty()) {
throw new RuntimeException("队列为空。");
}
return queue.poll();
}
public static void main(String[] args) {
MyQueue myQueue = new MyQueue();
myQueue.enqueue(10);
myQueue.enqueue(20);
myQueue.enqueue(30);
System.out.println("队列大小: " + myQueue.size());
System.out.println("出队元素: " + myQueue.dequeue());
System.out.println("队列大小: " + myQueue.size());
}
}```