双向链表--Java实现

时间:2022-11-10 09:09:02
 /*双向链表特点:
*1.每个节点含有两个引用,previos和next,支持向前或向后的遍历(除头节点)
*2.缺点插入或删除的时候涉及到引用修改的比较多
*注意:下面的双向链表其实也实现了双端链表
*注意:在Java中多个引用可以指向同一个对象,也可以随时改变引用的指向
* 关于修改引用细心一点就可以 引用A = 引用B 表示A引用指向B引用指向的对象
*应用:利用双向链表可以实现双端队列
* */ public class MyDoubleLink {
private Link first;
private Link last; public boolean isEmpty(){
return first == null;
} public void insertFirst(int key){
Link newLink = new Link(key);
if(first == null){
last = newLink;
}
else{
first.previous = newLink;
}
newLink.next = first;//链未断可以指向同一个
first = newLink;
} public void insertLast(int key){
Link newLink = new Link(key);
if(first == null){
first = newLink;
}
else{
last.next = newLink;
newLink.previous = last;
}
last = newLink;
} //插入指定值的后边---其实是一种尾巴插入--此时链表非空才可以操作
public boolean insertAfter(int key,int value){
Link newLink = new Link(value);
Link current = first;
while(current.id != key){
current = current.next;
if(current == null){
return false;
}
}
if(current == last){//find it at last item
newLink.next = null;
last = newLink;
}
else{
newLink.next = current.next;
current.next.previous = newLink;
}
newLink.previous = current;
current.next = newLink;
return true;
} public Link deleteFirst(){
Link temp = first;
if(first.next == null){
last = null;
}
else{
first.next.previous = null;
}
first = first.next;
return temp;
} public Link deleteLast(){
Link temp = last;
if(first.next == null){
first = null;
}
else{
last.previous.next = null;
}
last = last.previous;
return temp;
} //按照值进行删除--可能存在找不到的时候
public Link delete(int key){
Link current = first;
while(current.id != key ){
current = current.next;
if(current == null){
return null;
}
}
if(current == first){//find it at first item并非只有一个节点
first = current.next;
}
else{ //find it not first item
current.previous.next = current.next;
} if(current == last){ //find it at last item
last = current.previous;
}
else{ //find it not last
current.next.previous = current.previous;
}
return current;
} public void diaplayFirstToLast(){
System.out.println("first to last");
Link current = first;
while(current != null){
System.out.print(current.id + " ");
current = current.next;
}
System.out.println();
} public void displayLastToFirst(){
System.out.println("last to first");
Link current = last;
while(current != null){
System.out.print(current.id + " ");
current = current.previous;
}
System.out.println();
}
}