队列环形数组实现两种实现

 

 

1

import java.util.Iterator;
//环形队列,数组容量应该比实际需要大一
public class Main {
public static void main(String[] args) {
ArrayQueue<Integer> a=new ArrayQueue<>(10);
a.push(1);
a.push(2);
a.push(3);
a.push(4);
a.push(5);
a.push(6);
a.push(7);
a.pop();
System.out.println(a.peekFirst());
System.out.println(a.peekLast());
Iterator<Integer> I=a.iterator();
while(I.hasNext())
{
System.out.println(I.next());
}
}
public static class ArrayQueue<E>
{
int capacity;
int head=0;
int tail=0;
E []array;

public ArrayQueue(int capacity) {
array=(E[])new Object[capacity+1];
}
public boolean push(E value)
{
if(full())
{
return false;
}
array[tail]=value;
tail=(tail+1)%array.length;//易错点
return true;
}
public E peekFirst()
{
if(isempty())
{
return null;
}
return array[head];
}
public E peekLast()
{
if(isempty())
{
return null;
}
if(tail-1<0)
{
tail=tail-1+5;
}
return array[tail-1];
}
public E pop()
{
if(isempty())
{
return null;
}
E p=array[head];
head=(head+1)%array.length;
return p;
}
public Iterator<E> iterator()
{
return new Iterator<E>() {
int p=head;
@Override
public boolean hasNext() {
return p!=tail;
}

@Override
public E next() {
E p1=array[p];
p=(p+1)%array.length;
return p1;
}
};
}
public boolean isempty()
{
return head==tail;
}
public boolean full()
{
return (tail+1)% array.length==head;
}

}
}
 
 
2
import java.util.Iterator;

//单向环形队列 数组容量与需要容量一致 如果满了head和tail也会重合
public class Main {
public static void main(String[] args) {
ArrayQueue<Integer> a=new ArrayQueue<>(10);
a.push(1);
a.push(2);
a.push(3);
a.push(4);
a.push(5);
a.push(6);
a.push(7);
a.pop();
System.out.println(a.peekFirst());
System.out.println(a.peekLast());
Iterator<Integer> I=a.iterator();
while(I.hasNext())
{
System.out.println(I.next());
}
}
public static class ArrayQueue<E>
{
int head=0;
int tail=0;
int size=0;
E []array;

public ArrayQueue(int capacity) {
array=(E[])new Object[capacity];
}
public boolean push(E value)
{
if(full())
{
return false;
}
array[tail]=value;
tail=(tail+1)%array.length;
size++;
return true;
}
public E peekFirst()
{
if(isempty())
{
return null;
}
return array[head];
}
public E peekLast()
{
if(isempty())
{
return null;
}
if(tail-1<0)
{
tail=tail-1+5;
}
return array[tail-1];
}
public E pop()
{
if(isempty())
{
return null;
}
E p=array[head];
head=(head+1)%array.length;
size--;
return p;
}
public Iterator<E> iterator()
{
return new Iterator<E>() {
int p=head;
int count=0;
@Override
public boolean hasNext() {
return count<size;
}

@Override
public E next() {
E p1=array[p];
p=(p+1)%array.length;
count++;
return p1;
}
};
}
public boolean isempty()
{
return size==0;
}
public boolean full()
{
return size== array.length;
}

}
}
posted @ 2023-09-25 19:43  赵千万  阅读(5)  评论(0编辑  收藏  举报