利用ArrayList 实现栈和队列操作
栈
import java.util.ArrayList;
public class MyStack {
private ArrayList<Integer> stack;
public MyStack() {
stack = new ArrayList<>();
}
public void push(int val) {
stack.add(val);
}
public int pop() {
if(isEmpty()) {
throw new IllegalStateException("Stack is empty");
}
int val = stack.remove(stack.size() - 1);
return val;
}
public int peek() {
if(isEmpty()) {
throw new IllegalStateException("Stack is empty");
}
return stack.get(stack.size() - 1);
}
public boolean isEmpty() {
return stack.isEmpty();
}
public int size() {
return stack.size();
}
public static void main(String[] args) {
MyStack stack = new MyStack();
stack.push(1);
stack.push(2);
stack.push(3);
System.out.println("Pop: " + stack.pop());
System.out.println("Peek: " + stack.peek());
System.out.println("Size: " + stack.size());
System.out.println("Is Empty: " + stack.isEmpty());
}
}
队列
import java.util.ArrayList;
public class MyQueue {
private ArrayList<Integer> queue;
public MyQueue() {
queue = new ArrayList<>();
}
public void enqueue(int element) {
queue.add(element);
}
public int dequeue() {
if (isEmpty()) {
throw new IllegalStateException("Queue is empty");
}
return queue.remove(0);
}
public int peek() {
if (isEmpty()) {
throw new IllegalStateException("Queue is empty");
}
return queue.get(0);
}
public boolean isEmpty() {
return queue.isEmpty();
}
public int size() {
return queue.size();
}
public static void main(String[] args) {
MyQueue queue = new MyQueue();
queue.enqueue(1);
queue.enqueue(2);
queue.enqueue(3);
System.out.println(queue.dequeue()); // Output: 1
System.out.println(queue.peek()); // Output: 2
System.out.println(queue.size()); // Output: 2
}
}
posted on 2024-06-13 13:25 Indian_Mysore 阅读(123) 评论(0) 收藏 举报
浙公网安备 33010602011771号