java数据结构之LinkedDeque2(用链表实现的双端双向队列,addBack时调用节点的构造函数稍有不同)

来源:互联网 发布:网络侠客行txt全集下载 编辑:程序博客网 时间:2024/06/05 11:27
 

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;

publicintlength;

// |----| |-----| |----|

// | first|--> | 4 | | 5 | | 3 | <--|last| length=3

// |----| |-----| |----|

privateclass DLNode<T> {

private Tdata;

public T getData() {

returndata;

}

publicvoidsetData(T data) {

this.data = data;

}

public DLNode<T>next;

public DLNode<T>pre;

 

publicDLNode(){

this.data=null;

next=null;

}

publicDLNode(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;

}

publicstaticvoid 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稍有不同

 

publicvoid 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稍有不同

publicvoid 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;

}

publicboolean isEmpty() {

returnfirst==null;

}

publicvoid clear() {

first=null;

last=null;

}

publicint getLength()

{

returnlength;

}

publicvoid display() {

DLNode<T> cur=last;

while(cur!=null){

//if(cur!=null)

System.out.print(cur.getData()+",");

cur=cur.pre;

}

System.out.println();

}

publicvoid enqueue(T newEntry) {

//TODO Auto-generated method stub

}

}