标签:虚拟 private vat fail bsp oid over 结构 package
基于链表的队列
当我们基于链表实现队列时,需要从一端加元素,另一端取出元素,就需要引入一个新的变量tail指向链表的尾部,此时,向尾部进行添加操作时间复杂度会变为O(1),然而删除操作还是需要从head向后遍历,所以此时选择链表尾为队尾,链表头为队首。
基于链表的实现的源码如下:
package queue;
import linkedList.LinkedList;
public class LinkedListQueue<E> implements Queue<E> {
private class Node<E>{
E e;
Node<E> next;
public Node(E e,Node next){
this.e = e;
this.next = next;
}
public Node(E e){
this(e, null);
}
public Node(){
this(null, null);
}
@Override
public String toString() {
return e.toString();
}
}
private Node<E> dummyHead; //虚拟头结点
private Node<E> tail; //指向链表尾节点的索引
private int size; //链表中元素的个数
public LinkedListQueue(){
dummyHead = new Node<>();
tail = dummyHead;
size = 0;
}
@Override
public int getSize() {
return size;
}
@Override
public boolean isEmpty() {
return size == 0;
}
@Override
public void enqueue(E e) {
tail.next = new Node<E>(e);
tail = tail.next;
size++;
}
@Override
public E dequeue() {
if (isEmpty()) {
throw new IllegalArgumentException("Dequeue failed.Dequeue is empty.");
}
Node<E> retNode = dummyHead.next;
dummyHead.next = retNode.next;
retNode.next = null;
if (dummyHead.next == null) {
tail = dummyHead;
}
size--;
return retNode.e;
}
@Override
public E getFront() {
if (isEmpty()) {
throw new IllegalArgumentException("GetFront failed.Queue is Empty.");
}
return dummyHead.next.e;
}
@Override
public String toString() {
StringBuilder res = new StringBuilder();
Node<E> cur = dummyHead.next;
res.append("Queue: front ");
while (cur != null) {
res.append(cur + "->");
cur = cur.next;
}
res.append("NULL ");
res.append("tail");
return res.toString();
}
}
标签:虚拟 private vat fail bsp oid over 结构 package
原文地址:https://www.cnblogs.com/tc971121/p/10017352.html