publicclass Link {
publiclong dData;
public Link next;
public Link previous;
publicLink(long dData){
this.dData=dData;
}
publicvoiddisplayLink(){
System.out.print(dData+" ");
}
}
publicclass DoubleLinkedList {
private Link first;
private Link last;
publicDoubleLinkedList(){
first=null;
last=null;
}
public boolean isEmpty(){
return (first==null);
}
publicvoidinsertFirst(long dd){
Link newLink = new Link(dd);
if(isEmpty()){
last=newLink;
}else{
first.previous=newLink;
}
newLink.next=first;
first=newLink;
}
publicvoidinsertLast(long dd){
Link newLink=new Link(dd);
if(isEmpty()){
first=newLink;
}
else{
last.next=newLink;
newLink.previous=last;
}
last=newLink;
}
public Link deleteFirst(){//delete first link
Link temp =first;
if(first.next==null){//if only one items
last=null;
}else{
first.next.previous=null;
}
first=first.next;
return temp;
}
public Link deleteLast(){//delete last link
Link temp =last;
if(first.next==null){//if only one items
first=null;
}else{
last.previous.next=null;
}
last=last.previous;
return temp;
}
public boolean insertAfter(long key,long dd){
Link current =first;
while(current.dData!=key){
current=current.next;
if(current==null){
returnfalse;//didn't find it
}
}
Link newLink = new Link(dd);
if(current==last){
newLink.next=null;
last=newLink;
}
else{
newLink.next=current.next;
current.next.previous=newLink;
}
newLink.previous=current;
current.next=newLink;
returntrue;
}
public Link deleteKey(long key){
Link current =first;
while(current.dData!=key){
current=current.next;
if(current==null)
returnnull;
}
if(current==first){
first=current.next;
}
else{
current.previous.next=current.next;
}
if(current==last){
last=current.previous;
}
else{
current.next.previous=current.previous;
}
return current;
}
publicvoiddisplayForward(){
Link current=first;
while(current!=null){
current.displayLink();
current=current.next;
}
System.out.println("");
}
//遍历publicvoiddisplayBackward(){
Link current = last;//start at endwhile(current!=null){
current.displayLink();
current=current.previous;
}
System.out.println("");
}
//insertAfter在某一特定元素后面插入
}