前面实现了顺序队列,这里实现链式队列。
设front和rear分别指向队头和队尾节点,入队操作将新节点链在队尾节点后,并使rear指向新队尾节点;出队操作,当队列不空时,取得队头节点,删除之,并使front指向后继节点。
直接上代码:
/**
* 链式队列类
* @author Administrator
*
*/
public class LinkedQueue {
private Node front,rear;
private int size; //存储节点个数
public LinkedQueue(){
this.front=this.rear=null;
}
//判断队列是否为空,若空返回ture
public boolean isEmpty(){
return this.front==null&&this.rear==null;
}
//在队尾添加元素
public boolean enQueue(Node node){
if(isEmpty())
this.front=node;
else
this.rear.setNext(node);
this.rear=node;
this.size++;
return true;
}
//队头元素出列
public Node deQueue(){
if(!isEmpty()){
Node node=this.front;
this.front=this.front.getNext();
if(this.front==null)
this.rear=null;
this.size--;
return node;
}
return null;
}
//返回节点个数
public int size(){
return this.size;
}
}
/**
* 节点类
* @author Administrator
*
*/
public class Node {
private Object data;
private Node next;
public void setData(Object data) {
this.data = data;
}
public void setNext(Node next) {
this.next = next;
}
public Object getData() {
return data;
}
public Node getNext() {
return next;
}
}
/**
* 测试类
* @author Administrator
*
*/
public class StuTest3 {
private String name;
private int score;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getScore() {
return score;
}
public void setScore(int score) {
this.score = score;
}
public static void main(String[] args) {
LinkedQueue que=new LinkedQueue();
for(int i=0;i<4;i++){
String s="abcd";
StuTest3 st=new StuTest3();
st.setName(s.charAt(i)+"");
st.setScore(i+1);
Node node=new Node();
node.setData(st);
que.enQueue(node);
}
int num=que.size();
for(int i=0;i<num;i++){
Node node=que.deQueue();
StuTest3 st=(StuTest3)node.getData();
System.out.println("姓名为:"+st.getName()+",学分为"+st.getScore());
}
}
}