java队列实现_Java队列实现

本文对比了两种队列实现方式:基于数组的有界队列和基于双端链表的无界队列。数组实现中,队列长度有限,插入和删除操作的时间复杂度为O(1),适合一般情况使用。而双端链表实现的队列长度不受限制,同样保持了O(1)的时间复杂度,提供了更大的灵活性。
摘要由CSDN通过智能技术生成

队列数组实现:队列长度有限,但是考虑到平时一般都使用有界队列,这应该也不算是个缺点

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)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值