单链表的插入操作,除了首结点之外必须在某个结点的后面进行,而在双向链表中,在一个已知的结点之前或之后都可以。
1)s.prev = p.prev;
<strong>public class DoubleLink { public Link first; public Link last; public DoubleLink() { // 构造器初始化 this.last = null; this.first = null; } public boolean isEmpty() { // 判断是否为空 return first == null; } public void insertFirst(int data) { // 将元素插入链表头 Link link = new Link(data); if (isEmpty()) last = link; // 如果为空,last需要改变 else first.prev = link; link.next = first; first = link; } public void insertLast(int data) { // 将元素插入链表尾 Link link = new Link(data); if (isEmpty()) last = link; else last.prev = link; link.prev = last; last = link; } public boolean insertAfter(int key, int idata) { // 在某元素后插入 Link current = first; while (current.data != key) { current = current.next; } Link link = new Link(idata); if (current == last) { link.next = null; last = link; } else { link.next = current.next; current.next.prev = link; } link.prev = current; current.next = link; return true; } public Link deleteKey(int key) { // 删除某项元素 Link current = first; while (current.data != key) { current = current.next; } first = current.next; if (current == last) last = current.prev; else current.next.prev = current.prev; return current; } public Link deleteFirst() { // 删除表开头的元素 Link temp = first; if (first.next == null) last = null; else first.next.prev = null; // first结点的next字段引用的链结点的prev字段 first = first.next; return temp; } public Link deleteLast() { // 删除表末尾的元素 Link temp = last; if (first.next == null) first = null; else last.prev.next = null; last = last.prev; return temp; } public void showFirst() {// 前向展示 Link current = last; while (current != null) { current.show(); current = current.prev; } } public void showLast() {// 后向展示 Link current = first; while (current != null) { current.show(); current = current.next; } } public static void main(String[] args) { DoubleLink dlink = new DoubleLink(); dlink.insertFirst(1); dlink.insertFirst(3); dlink.insertFirst(2); dlink.insertAfter(2, 4); dlink.showFirst(); } } class Link { public int data; // 存放的数据 public Link prev;// 对前一项的引用,直接前驱 public Link next;// 对后一项的引用,直接后继 public Link(int data) { this.data = data; } public void show() { System.out.println(data + " "); } }</strong>
原文地址:http://blog.csdn.net/qq_21394609/article/details/44871175