双向链表逻辑图:
1.BookNode类
public class BookNode {
/**
* 图书的编号
*/
public int id;
/**
* 图书的名称
*/
public String name;
/**
* 图书的价格
*/
public double price;
/**
* 当前图书节点的上一个节点,前驱
*/
public BookNode preNode;
/**
* 当前图书节点的下一个节点,后继
*/
public BookNode nextNode;
public BookNode(int id, String name, double price) {
this.id = id;
this.name = name;
this.price = price;
}
@Override
public String toString() {
return "BookNode{" +
"id=" + id +
", name='" + name + '\'' +
", price=" + price +
'}';
}
}
2.BookLinked 类
public class BookLinked {
/**
* 双向链表,头节点
*/
public BookNode head = new BookNode(0,"0",0.0);
/**
* 向双向链表中添加一个节点
*/
public void addNode(BookNode bookNode){
BookNode temp = head;
while (true){
//当双向链表为空或当前在链表的最后一个节点时会执行
if (temp.nextNode == null){
temp.nextNode = bookNode;
bookNode.preNode = temp;
return;
}
//一个节点,插入到两个节点中间
if (temp.nextNode.id>bookNode.id){
bookNode.nextNode = temp.nextNode;
temp.nextNode.preNode = bookNode;
temp.nextNode = bookNode;
bookNode.preNode = temp;
return;
}
temp = temp.nextNode;
}
}
/**
* 对双向链表中某一个节点进行修改
*/
public void updateNode(BookNode bookNode) {
BookNode temp = head;
while (true){
if (temp.nextNode == null){
System.out.println("空链表或链表没有此数据,不能进行更新");
return;
}
if (temp.nextNode.id == bookNode.id){
temp.nextNode.name = bookNode.name;
temp.nextNode.price = bookNode.price;
return;
}
temp = temp.nextNode;
}
}
/**
* 对双向链表中某一个节点进行删除
*/
public void deleteNodeById(int id){
BookNode temp = head;
while (true){
if (temp.nextNode == null){
System.out.println("空链表或链表,不能进行删除");
return;
}
if (temp.nextNode.id == id){
if (temp.nextNode.nextNode == null){
//删除最后一个元素
temp.nextNode.preNode = null;
temp.nextNode = null;
return;
}
temp.nextNode.nextNode.preNode = temp;
temp.nextNode = temp.nextNode.nextNode;
return;
}
temp = temp.nextNode;
}
}
/**
* 对双向链表进行查询
*/
public void queryBookLinked(){
BookNode temp = head;
if (temp.nextNode == null){
System.out.println("空链表");
return;
}
while (true){
if (temp.nextNode != null){
System.out.println(temp);
}else{
System.out.println(temp);
break;
}
temp = temp.nextNode;
}
}
}