java创建循环队列代码 java循环队列queue( 二 )


public boolean isEmpty()
{
return list.isEmpty();
}
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
LinkedListQueueTest llq=new LinkedListQueueTest();
System.out.println(llq.isEmpty());
llq.enqueue("147");
llq.enqueue("258");
llq.enqueue("369");
System.out.println(llq.size());
System.out.println("移除队列头元素java创建循环队列代码:"+llq.dequeue());
System.out.println(llq.size());
llq.enqueue("abc");
llq.enqueue("def");
System.out.println(llq.size());
System.out.println("查看队列java创建循环队列代码的头元素:"+llq.front());
System.out.println(llq.size());
System.out.println(llq.isEmpty());
}
}
通过数组实现
package 队列和堆栈;
import java.util.NoSuchElementException;
//通过数组来实现队列
public class ArrayQueue {
//字段
publicstaticObject[] data;
//队列的元素个数
protected int size ;
//队列头
protected int head;
//队列尾
public staticint tail;
/**
*
*/
//无参数构造函数
public ArrayQueue() {
final int INITIAL_LENGTH=3;
data=https://www.04ip.com/post/new Object[INITIAL_LENGTH];
size=0;
head=0;
tail=-1;
}
//队列元素个数方法
public int size()
{
return size;
}
public boolean isEmpty()
{
return size==0;
}
//得到队列头元素
public Object front()
{
if(size==0)
throw new NoSuchElementException();
return data[head];
}
//进入队列enqueue()方法
public void enqueue(Object obj)
{
//此时队列已经满
if(size==data.length){
Object[] oldData=https://www.04ip.com/post/data;
data=https://www.04ip.com/post/new Object[data.length*2];
//if(head==0)
System.arraycopy(oldData, head, data, 0, oldData.length-head);
if(head0)
System.arraycopy(oldData, 0, data, head+1, tail+1);
head=0;
tail=oldData.length-1;
}
tail=(tail+1)%data.length;
size++;
data[tail]=obj;
}
//队列的元素出队
public Object dequeue()
{
if(size==0)
throw new NoSuchElementException();
Object ele=data[head];
//循环队列
head=(head+1)%data.length;
size--;
return ele;
}
@Override
public String toString() {
// TODO Auto-generated method stub
return super.toString();
}
}
通过向量实现:
//通过向量实现栈
package 队列和堆栈;
import java.util.*;
public class VectorStackTest {
//字段
Vectorv;
//构造函数
public VectorStackTest()
{
v=new Vector();
}
//元素的个数
public int size()
{
return v.size();
}
//是否为空
public boolean isEmpty()
{
return size()==0;
}
//进栈
public Object Push(Object obj)
{
v.addElement(obj);
return obj;
}
//出栈方法
public Object Pop()
{
int len=size();
Object obj=Peek();
v.removeElementAt(len-1);
return obj;
}
//查看栈顶元素
public Object Peek()
{
int len = size();
if (len == 0)
throw new EmptyStackException();
return v.elementAt(len - 1);
}
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
VectorStackTest vst=new VectorStackTest();
System.out.println("大?。?+vst.size());
vst.Push("123");
vst.Push("456");
vst.Push("789");

推荐阅读