public class GeneralizedQueue< Item>
支持如下API
isEmpty()
insert(Item item) 添加一个元素
delete(int k) 删除并返回最早插入的第k个元素
方法一 链表实现
public class GeneralizedQueue <Item>{
private class Node {
Item item;
Node next;
}
private Node head;//指向队头
private Node tail;//指向队尾
int N;
public GeneralizedQueue (){
N = 0;
}
public boolean isEmpty() {
return N == 0;
}
public int size() {
return N;
}
public void insert(Item item) {
Node newNode = new Node();
newNode.item = item;
if(isEmpty()) {
head = newNode;
tail = newNode;
}else {
tail.next = newNode;
tail = newNode;
}
N++;
}
//删除并返回最早插入的第k个元素
public Item delete(int k) {
if(k<0 ||k > N) {
System.out.println("输入参数为负或过大");
return null;
}
int i = 1;
Node temp = head;
Node pre = null;
while (i < k) {
pre = temp;
temp = temp.next;
i++;
}
if(pre == null){
if(head.next != null) {
head = head.next;
} else{
head = null;
N--;
return temp.item;
}
}else {
pre.next = temp.next;
}
N--;
return temp.item;
}
}
方法二 数组实现
此时采用动态数组进行插入实现
package al1_3;
public class GeneralizedQueue <Item>{
private Item[] array;
private int N;
public GeneralizedQueue() {
array = (Item[]) new Object[5];
N = 0;
}
public boolean isEmpty() {
return N==0;
}
public int size() {
return N;
}
private void resize(int max){
Item[] temp = (Item[]) new Object[max];
System.arraycopy(array,0,temp,0,array.length);
array = temp;
}
public void insert(Item item) {
if(N == array.length) {
resize(2*array.length);
}
array[N++] = item;
}
public Item delete(int k){
if(N == 0) {
System.out.println("队列已空");
return null;
}
if(k>N || k<0) {
System.out.println("输入参数为负或过大");
return null;
}
Item temp = array[k-1];
if (array.length - k >= 0)
System.arraycopy(array, k, array, k - 1, array.length - k);
N--;
if(N>0 && N < array.length/4)
resize(array.length/2);
return temp;
}
}