package com.jimmy.impl;
import com.jimmy.QueueInterf;
public class DoubleDirectionLinkedQueue<T> implements QueueInterf<T> {
/**
* @param args
*/
public DLNode<T> first;
public DLNode<T> last;
public int length;
// |----| |-----| |----|
// | first|--> | 4 | | 5 | | 3 | <--|last| length=3
// |----| |-----| |----|
private class DLNode<T> {
private T data;
public T getData() {
return data;
}
public void setData(T data) {
this.data = data;
}
public DLNode<T> next;
public DLNode<T> pre;
public DLNode(){
this.data=null;
next=null;
}
public DLNode(T data){
this.data=data;
next=null;
}
public DLNode(T data,DLNode<T> next){
this.data=data;
this.next=next;
}
}
public DoubleDirectionLinkedQueue(){
first=null;
last=null;
}
public static void main(String[] args) {
DoubleDirectionLinkedQueue<Integer> q=new DoubleDirectionLinkedQueue<Integer>();
q.addFront(4);
q.addFront(5);
q.addFront(3);
q.display();
//q.dequeue();
//q.dequeue();
//q.display();
}
//在前面插入,调用构造函数有第一种linkedQueue稍有不同
public void addFront(T newEntry) {
DLNode<T> newDLNode=new DLNode<T>(newEntry,null);
if(isEmpty())
{
first=newDLNode;
last=newDLNode;
// |----|
// | first|--> | 4 | <--|last|
// |----|
}else{
//这里与第一种linkedQueue得写法也稍有不同
first.pre=newDLNode;
newDLNode.next=first;
first=newDLNode;
}
length++;
}
//在后面插入,调用构造函数有第一种linkedQueue稍有不同
public void addBack(T newEntry) {
DLNode<T> newDLNode=new DLNode<T>(newEntry,null);
if(isEmpty())
{
first=newDLNode;
last=newDLNode;
// |----|
// | first|--> | 4 | <--|last|
// |----|
}else{
//这里与第一种linkedQueue得写法也稍有不同
last.next=newDLNode;
newDLNode.pre=last;
last=newDLNode;
}
length++;
}
public T dequeue() {
T front=null;
if(!isEmpty())
{
front=first.getData();
first=first.next;
}
length--;
return front;
}
public T getFront() {
T front=null;
if(!isEmpty())
{
front=first.getData();
}
return front;
}
public boolean isEmpty() {
return first==null;
}
public void clear() {
first=null;
last=null;
}
public int getLength()
{
return length;
}
public void display() {
DLNode<T> cur=last;
while(cur!=null){
//if(cur!=null)
System.out.print(cur.getData()+",");
cur=cur.pre;
}
System.out.println();
}
public void enqueue(T newEntry) {
// TODO Auto-generated method stub
}
}