Java队列实现
队列数组实现:队列长度有限,但是考虑到平时一般都使用有界队列,这应该也不算是个缺点
public class Queue { private Object[] objs; private int head; private int end; private int size; public Queue(int size){ objs = new Object[size]; this.head = 0; this.end = -1; this.size = 0; } public void push(Object obj) throws Exception{ if(this.size > objs.length) throw new Exception("Queue is full!"); if(end == objs.length - 1) end = -1; objs[++end] = obj; size++; } public Object pop() throws Exception{ if(this.size == 0) throw new Exception("Queue is empty!"); Object tmp = objs[head++]; if(head == objs.length) head = 0; size--; return tmp; } public Object peek() throws Exception{ if(this.size == 0) throw new Exception("Queue is empty!"); return objs[head]; } public int size(){ return this.size; } public boolean isEmpty(){ return (size == 0); } public boolean isFull(){ return (size == objs.length); } }
插入和删除的时间复杂度都为O(1)
队列双端链表实现:
public class FirstLastList { private class Data{ private Object obj; private Data next = null; Data(Object obj){ this.obj = obj; } } private Data first = null; private Data last = null; public void insertFirst(Object obj){ Data data = new Data(obj); if(first == null) last = data; data.next = first; first = data; } public Object deleteFirst() throws Exception{ if(first == null) throw new Exception("empty"); Data temp = first; if(first.next == null) last = null; first = first.next; return temp.obj; } public void display(){ if(first == null) System.out.println("empty"); System.out.print("first -> last : | "); Data cur = first; while(cur != null){ System.out.print(cur.obj.toString() + " | "); cur = cur.next; } System.out.print("\n"); } }
public class FirstLastListQueue { private FirstLastList fll = new FirstLastList(); public void push(Object obj){ fll.insertLast(obj); } public Object pop() throws Exception{ return fll.deleteFirst(); } public void display(){ fll.display(); } public static void main(String[] args) throws Exception{ FirstLastListQueue fllq = new FirstLastListQueue(); fllq.push(1); fllq.push(2); fllq.push(3); fllq.display(); System.out.println(fllq.pop()); fllq.display(); fllq.push(4); fllq.display(); } }
first -> last : | 1 | 2 | 3 | 1 first -> last : | 2 | 3 | first -> last : | 2 | 3 | 4 |
长度不受限制并且插入和删除的时间复杂度都为O(1)