什么是双向链表?
每一个结点不仅配有next引用,同时还有一个prev引用,指向其上一个结点(前驱结点), 没有前驱的时候就为NULL。
(以下图片均来自网络,侵删)
与单链表的区别?
和单向链表相比有以下优势:
- 插入删除不需要移动元素外,可以原地插入删除
- 可以双向遍历
插入操作
删除操作
实现
public class DLNode { Object data; DLNode prev; DLNode next; static DLNode head; static DLNode tail; // 无参构造 public DLNode() { super(); } // 有参构造 public DLNode(Object data, DLNode prev, DLNode next) { super(); this.data = data; this.prev = prev; this.next = next; } // 获取数据 public Object getData() { return data; } // 修改数据 public void setData(Object data) { this.data = data; } // 得到前驱结点 public DLNode getPrev() { return prev; } // 修改前驱结点 public void setPrev(DLNode prev) { this.prev = prev; } // 获取后驱结点 public DLNode getNext() { return next; } // 修改后驱结点 public void setNext(DLNode next) { this.next = next; } // 获取长度 public static int getLength() { int count = 0; for (DLNode n = head; n != null; n = n.next) { count++; } return count; } // 插入结点 public static void add(Object data, int index) { DLNode node = new DLNode(data, null, null); if (index == 0) { node.next = head; node.prev = null; head = node; } else if (index == getLength()) { tail.next = node; node.prev = tail; tail = node; } else { int temp = 0; for (DLNode n = head; n != null; n = n.next) { temp++; if (temp == index) { node.next = n.next; n.next.prev = node; n.next = node; node.prev = n; break; } } } } //删除结点 public static void remove(int index) { if (index == 0) { head = head.next; head.prev = null; } else if (index == getLength() - 1) { tail = tail.prev; tail.next = null; } else if (index >= getLength()) { System.out.println("超出链表长度"); System.exit(0); } else { int temp = 0; for (DLNode n = head; n != null; n = n.next) { temp++; if (temp == index) { n.next = n.next.next; n.next.prev = n; break; } } } } public static void main(String[] args) { DLNode node1 = new DLNode("aaa", null, null); DLNode node2 = new DLNode("bbb", node1, null); DLNode node3 = new DLNode("ccc", node2, null); DLNode node4 = new DLNode("ddd", node3, null); node3.setNext(node4); node2.setNext(node3); node1.setNext(node2); head = node1; tail = node4; System.out.print("当前链表:"); for (DLNode n = head; n != null; n = n.next) { System.out.print(n.data + " "); } System.out.println(); System.out.println("链表长度:" + getLength()); add("eee", 4); System.out.print("插入后链表:"); for (DLNode n = head; n != null; n = n.next) { System.out.print(n.data + " "); } System.out.println(); remove(0); System.out.print("删除后链表:"); for (DLNode n = head; n != null; n = n.next) { System.out.print(n.data + " "); } } }