Java中的队列
import java.util.Queue;
import java.util.LinkedList;
public class QueueExample {
public static void main(String[] args) {
// 创建一个Queue对象
Queue<String> queue = new LinkedList<>();
// 添加元素到队列
queue.add("Apple");
queue.add("Banana");
queue.add("Orange");
// 获取队列头部元素
String head = queue.peek();
System.out.println("头部元素:" + head);
// 遍历队列并输出元素
System.out.println("队列元素:");
for (String element : queue) {
System.out.println(element);
}
// 移除队列头部元素
String removedElement = queue.remove();
System.out.println("移除的元素:" + removedElement);
// 队列大小
int size = queue.size();
System.out.println("队列大小:" + size);
// 判断队列是否为空
boolean isEmpty = queue.isEmpty();
System.out.println("队列是否为空:" + isEmpty);
}
}
队列模拟栈
栈是后进先出的数据结构
队列是先进先出的数据结构
package 队列;
import java.util.LinkedList;
import java.util.Queue;
public class leetcode225 {
public static void main(String[] args) {
}
}
class MyStack {
Queue<Integer> queue1;
Queue<Integer> queue2;
public MyStack() {
queue1 = new LinkedList<Integer>();
queue2 =new LinkedList<Integer>();
}
public void push(int x) {
//队列插入元素
queue2.offer(x);
//如果不是空
while (!queue1.isEmpty()){
//删除并返回元素 1就是空了
queue2.offer(queue1.poll());
}
//然后1=2
//2又是空
Queue<Integer> temp = queue1;
queue1 = queue2;
queue2 = temp;
}
public int pop() {
return queue1.poll();
}
public int top() {
return queue1.peek();
}
public boolean empty() {
return queue1.isEmpty();
}
}