java实现链队列的类代码:
package linkqueue; public class LinkQueue { class Element
{
Object elem;
Element next;
} private Element front;
private Element rear;
private Element header = null; /**
* 初始化队列
* */
void initQueue()
{
header = new Element();
front = new Element();
rear = new Element();
front=header;
rear=header;
} /**
* 向队列插入元素
* */
void enQueue(Object o)
{
Element e=new Element();
e.elem=o;
if(rear==header)//第一次插入元素
{
rear=e;
header.next=e;
front.next=e;
}else
{
rear.next=e;
rear=e;
}
} /**
* 出队
* */
Object deQueue()
{
Object o = null;
if(rear==header)
{
System.out.println("队列为空!");
}else
{
o=front.next.elem;
if(front.next==rear)//队中只有一个元素
{
front.next=header;
rear=header;
}else//队中大于一个元素
{
front.next=front.next.next;
}
}
return o;
} /**
* 打印队列
* */
void print()
{
System.out.print("打印队列:");
Element temp = front;
while(temp!=rear)
{
System.out.print(temp.next.elem+"\t");
temp=temp.next;
}
System.out.println();
}
}
测试类代码:
package linkqueue; public class LinkQueueMain { public static void main(String[] args) {
LinkQueue lQueue = new LinkQueue();
lQueue.initQueue();
System.out.println("出队操作:"+lQueue.deQueue());
lQueue.enQueue(1);
lQueue.enQueue(2);
lQueue.enQueue(3);
lQueue.enQueue(4);
lQueue.enQueue(5);
lQueue.print(); System.out.println("出队操作:"+lQueue.deQueue());
System.out.println("出队操作:"+lQueue.deQueue());
lQueue.print(); System.out.println("出队操作:"+lQueue.deQueue());
System.out.println("出队操作:"+lQueue.deQueue());
lQueue.print(); System.out.println("出队操作:"+lQueue.deQueue());
System.out.println("出队操作:"+lQueue.deQueue());
lQueue.print(); } }