1、普通队列
FIFO、全称:First In, First Out、中文意思:先进先出
offer / poll / peek(安全)或add / remove / element(严格(为null会抛异常))
publicstaticvoidmain(String[]args){// 用 LinkedList 实现普通队列Queue<Integer>queue=newArrayDeque<>();// 入队offerqueue.offer(1);queue.offer(2);queue.offer(3);// 查看队首peekSystem.out.println(queue.peek());// 1// 出队pollSystem.out.println(queue.poll());// 1System.out.println(queue.poll());// 2// 再出队System.out.println(queue.poll());// 3System.out.println(queue.poll());// null}2、双端队列
publicstaticvoidmain(String[]args){Deque<Integer>deque=newArrayDeque<>();// 队尾入队deque.offerLast(1);deque.offerLast(2);// 队首入队deque.offerFirst(0);// 查看队首和队尾System.out.println(deque.peekFirst());// 0System.out.println(deque.peekLast());// 2// 出队System.out.println(deque.pollFirst());// 0System.out.println(deque.pollLast());// 2}3、栈
LIFO、后进先出
publicstaticvoidmain(String[]args){// 创建一个栈(使用 ArrayDeque)Deque<String>stack=newArrayDeque<>();// 1. push(E e) 压栈stack.push("苹果");stack.push("香蕉");stack.push("橘子");System.out.println("压栈后: "+stack);// [橘子, 香蕉, 苹果]// 2. peek() 查看栈顶元素Stringtop=stack.peek();System.out.println("栈顶元素: "+top);// 橘子System.out.println("查看后栈: "+stack);// 栈内容不变// 3. pop() 弹栈Stringremoved=stack.pop();System.out.println("弹出的元素: "+removed);// 橘子System.out.println("弹栈后栈: "+stack);// [香蕉, 苹果]// 4. isEmpty() 判断栈是否为空System.out.println("栈是否为空? "+stack.isEmpty());// false// 5. size() 栈中元素数量System.out.println("栈中元素数量: "+stack.size());// 2// 再弹一次stack.pop();stack.pop();System.out.println("全部弹出后,栈是否为空? "+stack.isEmpty());// true}