java 数据结构队列的代码实现,可以简单的进行入队列和出队列的操作
/**
* java数据结构之队列的实现
* 2016/4/27
**/
package cn.Link;
import java.util.*; public class Queue{
Node tail = new Node();
Node nowNode = new Node(); //永远指向队首
int size;
Queue(){};
Queue(String date){
this.tail.date = date;
this.tail.next = null;
this.nowNode.next = this.tail;
this.size = 1;
System.out.println("队列已经被建立,"+date+"被加入到队列中");
} //节点类
class Node{
String date;
Node next;
Node(){};
Node(String date){
this.date = date;
}
} //向队列中插入数据
public void EnQueue(String date){
Node preNode = new Node(date);
preNode.next = this.nowNode.next;
this.nowNode.next = preNode;
this.size++;
System.out.println("数据"+date+"被加入到队列中");
} //出队列操作
public void DeQueue(){
Node preNode = new Node();
preNode.next = this.nowNode.next;
while(true){
if(preNode.next.next != this.tail){
preNode.next = preNode.next.next;
}else{
preNode.next.next = null;
this.tail = preNode.next;
System.out.println("出队列完成~~~"); break;
}
}
this.size--;
} //遍历队列输出
public void PrintQueue(){
Node preNode = new Node();
preNode.next = this.nowNode.next;
System.out.print("遍历输出队列: ");
while(preNode.next != null){
System.out.print(" -->"+preNode.next.date);
preNode.next = preNode.next.next;
}
System.out.println("+++++++++++当前队列的长度为"+this.size);
} //清空队列
public void clear(){
this.nowNode.next = null;
this.tail = null;
this.size = 0;
System.out.println("队列已被清空"); } public static void main(String[] args){
Queue queue = new Queue("sum1");
queue.EnQueue("sum2");
queue.EnQueue("sum3");
queue.EnQueue("sum4");
queue.EnQueue("sum5");
queue.EnQueue("sum6");
queue.EnQueue("sum7");
queue.EnQueue("sum8");
queue.PrintQueue();
queue.DeQueue();
queue.DeQueue();
queue.PrintQueue();
}
}