一.队列的概念
队列
:只允许
在一端
进行
插入
数据操作,在
另一端
进行
删除
数据操作的特殊线性表,队列具有
先进先出 入队列
:进行插入操作的一端称为
队尾
出队列
:进行删除操作的一端称为
队头
在
Java
中,
Queue
是个接口,底层是通过链表实现
的
二.队列的使用
注意
:
Queue
是个接口,在实例化时
必须实例化LinkedList的对象
,因为
LinkedList
实现了
Queue
接口。
例:Queue<Integer> queue=
new LinkedList<>()
;
方法 | 功能 |
queue.offer(val) | 入队列 |
queue.poll() | (头元素)出队列 |
queue.peek() | 获取顶元素 |
queue.size() | 获取元素个数 |
queue.isEmpty() | 判断是否为空 |
三.队列的模拟实现
public class MyQueue { public static void main(String[] args) { MyQueue q=new MyQueue(); q.offer(1); q.offer(2); System.out.println(q.peek()); System.out.println(q.poll()); System.out.println(q.peek()); System.out.println(q.size); System.out.println(q.isEmpty()); } static class ListNode{//双链表 public int val; public ListNode per; public ListNode next; public ListNode(int val){ this.val=val; } } public ListNode last=null; public ListNode first=null; public int size=0; public void offer(int val){ ListNode noue=new ListNode(val); if(size==0){ first=last=noue; }else { noue.per=last; last.next=noue; last=last.next; } size++; } public int poll(){ if(isEmpty()){ int sum= first.val; size--; first=first.next; first.per=null; return sum; } return -1; } public int peek(){ if(isEmpty()){ int sum= first.val; return sum; } return -1; } public boolean isEmpty(){ if(size==0){ return false; } return true; } }