双向链表也叫双链表,是链表的一种,它的每个数据结点中都有两个指针,分别指向直接后继和直接前驱。所以,从双向链表中的任意一个结点开始,都可以很方便地访问它的前驱结点和后继结点。
BookNode.java
package data_structure; 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 + '}'; } }
DualLinkedList.java
package data_structure; public class DualLinkedList { private final BookNode head = new BookNode(0, "", 0.0); /** * 添加结尾新的节点 */ public void addLast(BookNode newNode) { BookNode temp = head; while (temp.next != null) { //如果第一次进来则进入,表示双向链表是空数据 temp = temp.next; } /* * 需要把新的节点给上一个节点 * 需要把上一个节点next指向新的节点 */ temp.next = newNode; newNode.pre = temp; } /** * 修改节点 * 条件:双向链表中的每一个结点的id和修改的id对比,如果对比成功,则进行修改该结点 * ,如果没有对比成功,双向链表中未找到目标结点 */ public void updateNode(BookNode node) { //是否是空链表 if (head.next == null) { System.out.println("空链表..."); return; } BookNode temp = head.next; boolean flg = false; while (true) { if (temp == null) { break; } if (temp.id == node.id) { flg = true; break; } temp = temp.next; } if (flg) { temp.name = node.name; temp.price = node.price; } else { System.out.println("未找到要修改的节点..."); } } /** * 双向链表删除 * 条件:根据id编号进行删除节点 */ public void delNode(int id) { if (head.next == null) { System.out.println("空链表..."); return; } BookNode temp = head.next; boolean flg = false; while (true) { if (temp == null) { break; } if (temp.id == id) { flg = true; break; } temp = temp.next; } if (flg) { temp.pre.next = temp.next; if (temp.next != null) { temp.next.pre = temp.pre; } } else { System.out.println("未找到该结点..."); } } public void list() { BookNode tempNode = head.next; while (tempNode != null) { System.out.println(tempNode.toString()); tempNode = tempNode.next; } } }
LinkedTest.java
package data_structure; /** * @company: 北京动力节点 * @author:韩国庆 */ public class LinkedTest { public static void main(String[] args) { DualLinkedList dualLinkedList = new DualLinkedList(); BookNode bookNode1 = new BookNode(1, "红楼梦", 66.00); BookNode bookNode2 = new BookNode(2, "西游记", 66.00); BookNode bookNode3 = new BookNode(3, "水浒传", 66.00); BookNode bookNode4 = new BookNode(4, "三国演义", 66.00); dualLinkedList.addLast(bookNode1); dualLinkedList.addLast(bookNode2); dualLinkedList.addLast(bookNode3); dualLinkedList.addLast(bookNode4); dualLinkedList.list(); dualLinkedList.delNode(1); System.out.println("------------------------------------------"); dualLinkedList.updateNode(new BookNode(3, "计算机", 66.00)); dualLinkedList.list(); } }
运行结果: