双链表的基本操作与演示
双链表节点结构如下图示:
双链表节点比单链表多一个前驱指针域。
基本操作代码
package com.ma.linked;
public class BookNode {
public int id;
public String name;
public double price;
//结点下一个结点,结点后继
public BookNode next;
//结点上一个结点,结点前缀
public BookNode pre;
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 +
'}';
}
}
package com.ma.linked;
public class DualLinkedList {
private BookNode head = new BookNode(0,"",0.0);
//增加结尾新的结点
public void addLast(BookNode node){
BookNode temp = head;
while (true){
//如果第一次进来就进入。表示双向链表是空数据
if (temp.next == null){
break;
}
temp = temp.next;
}
//需要把新的结点给上一个结点
//需要把上一个结点的next指向新节点
//把新结点的pre指向上一个结点
temp.next = node;
node.pre = temp;
}
//修改结点
//条件:双向链表中的每一个结点id和要修改的结点id对比,如果对比成功,则进行修改,如果没有对比成功,则双向链表中未找到相应结点
public void updateNode(BookNode node){
if (head.next == null){
return;
}
BookNode temp = head.next;
boolean flag = false;
while (true){
if (temp == null){
break;
}
if (temp.id == node.id){
flag = true;
break;
}
temp = temp.next;
}
if (flag){
temp.name = node.name;
temp.price = node.price;
}else {
System.out.println("未找到该节点");
}
}
//双链表删除
public void delNode(int id){
if (head.next == null){
return;
}
BookNode temp = head.next;
boolean flag = false;
while (true){
if (temp == null){
break;
}
if (temp.id == id){
flag = true;
break;
}
temp = temp.next;
}
if (flag){
temp.pre.next = temp.next;
if (temp.next != null){
temp.next.pre = temp.pre;
}
}
}
//双链表展示
public void list(){
if (head.next == null){
return;
}
BookNode temp = head.next;
while (true){
if (temp == null){
break;
}
System.out.println(temp);
temp = temp.next;
}
}
}
演示代码
package com.ma.linked;
public class Linked2Test {
public static void main(String[] args) {
BookNode bookNode1 = new BookNode(1, "三国演义", 66.6);
BookNode bookNode2 = new BookNode(2,"西游记",66.6);
BookNode bookNode4 = new BookNode(4,"水浒传",66.6);
BookNode bookNode3 = new BookNode(3,"红楼梦",66.6);
DualLinkedList dualLinkedList = new DualLinkedList();
dualLinkedList.addLast(bookNode1);
dualLinkedList.addLast(bookNode2);
dualLinkedList.addLast(bookNode3);
dualLinkedList.addLast(bookNode4);
dualLinkedList.addLast(new BookNode(6,"伏天氏",111.1));
dualLinkedList.delNode(6);
dualLinkedList.list();
}
}
dLast(bookNode4);
dualLinkedList.addLast(new BookNode(6,"伏天氏",111.1));
dualLinkedList.delNode(6);
dualLinkedList.list();
}
}