队列最大的特点就是:先进先出,把握这个特点后,我们很容易用双端链表实现一个队列
/**
* 双端链表类
* @author zhang
*
*/
public class FirstLastList {
private Link first;
private Link last;
public FirstLastList(){
first=null;
last=null;
}
public boolean isEmpty(){
return first==null;
}
public void insertLast(long dd){
Link newLink = new Link(dd);
if(isEmpty()){
first=newLink;
}else{
last.next = newLink;
}
last=newLink;
}
public long deleteFirst(){
long temp=first.dData;
if(first.next==null){
last=null;
}
first=first.next;
return temp;
}
public void displayList(){
Link current=first;
while(current!=null){
current.displayLink();
current=current.next;
}
System.out.println();
}
}
/**
* 双端链表实现队列
* @author zhang
*
*/
public class LinkQueue {
private FirstLastList theList;
public LinkQueue(){
theList=new FirstLastList();
}
public boolean isEmpty(){
return theList.isEmpty();
}
public void insert(long j){//插入从队尾插
theList.insertLast(j);
}
public long remove(){//删除从队头删
return theList.deleteFirst();
}
public void displayQueue(){
System.out.print("Queue(font-->rear):");
theList.displayList();
}
}
/**
* 链接点类
*
* @author zhang
*
*/
public class Link {
public long dData;
public Link next;
public Link(long dData) {
this.dData = dData;
}
public void displayLink() {
System.out.print(dData + " ");
}
}