
import java.util.LinkedList;
import java.util.Queue;
public class QueueDemo {
public static void main(String[] args) {
// 创建队列(LinkedList实现Queue接口)
Queue<String> queue = new LinkedList<>();
// 1. 入队操作(添加元素)
queue.offer("A"); // 推荐:添加成功返回true → [A]
queue.offer("B"); // → [A, B]
queue.offer("C"); // → [A, B, C]
// queue.add("D"); // 等价于offer,队列无界时总能成功
System.out.println("入队后队列:" + queue); // [A, B, C]
// 2. 查看队首(不删除)
String head = queue.peek(); // 获取队首A,队列不变 → [A, B, C]
System.out.println("队首元素(peek):" + head); // A
// String element = queue.element(); // 等价于peek,空队列时抛异常
// 3. 出队操作(删除并返回队首)
String polled1 = queue.poll(); // 删除并返回A → [B, C]
System.out.println("出队元素(poll):" + polled1); // A
String polled2 = queue.poll(); // 删除并返回B → [C]
System.out.println("出队后队列:" + queue); // [C]
// String removed = queue.remove(); // 等价于poll,空队列时抛异常
// 4. 空队列测试(peek/poll返回null,更安全)
queue.poll(); // 删除最后一个元素C → 空队列
String emptyPeek = queue.peek(); // 空队列返回null
String emptyPoll = queue.poll(); // 空队列返回null
System.out.println("空队列peek:" + emptyPeek + ",poll:" + emptyPoll); // null null
}
}
package MyQueue;
import org.w3c.dom.ls.LSInput;
/**
* Created with IntelliJ IDEA.
* Description:
* User: czt20
* Date: 2025 -12-18
* Time: 21:53
*/
public class MyQueue {
static class ListNode{
public int val;
public ListNode pre;
public ListNode next;
public ListNode(int val) {
this.val = val;
}
}
public ListNode first=null;
public ListNode last=null;
public int usedsize=0;
ListNode cur=first;
public void offer(int val){
ListNode node=new ListNode(val);
if (isEmpty()){
first=last=node;//first和last连接就靠这里!!!!!!!!!!
}
last.next=node;
node.pre=last;
last=node;
usedsize++;
}
public int poll(){
if (first==null){
return -1;
}
ListNode curN=first;
first=first.next;
if(first!=null){
first.pre=null;
}
usedsize--;
return curN.val;
}
public int size(){
return usedsize;
}
public int peek(){
return first.val;
}
public boolean isEmpty(){
if (first==null){
return true;
}
return false;
}
}