JAVA 双链表
/* * 不带头节点的 */ public class Doublelinkedlist<T> { class node<T> { T data; node next, pre; public node() { } public node(T data) { this.data = data; } } private node<T> head; private node<T> tail; private int length; public Doublelinkedlist() { length = 0; head = null; tail = head; } boolean isEmpty() { return length == 0; } void addFirst(T data) { node<T> tmp = new node(data); if (isEmpty()) { head = tmp; tail = tmp; } else { tmp.next = head; head = tmp; } length++; } void addLast(T data)// 默认尾节点插入 { node<T> tmp = new node(data); if (isEmpty()) { head = tmp; tail = tmp; } else { tail.next = tmp; tmp.pre = tail; tail = tmp; } length++; } int length() { return length; } T getElum(int index)// 为了简单统一从头找 { if (index > length - 1) { System.out.println("index is wrong!!!"); return null; } node<T> tmp = head; for (int i = 0; i < index; i++) { tmp = tmp.next; } return tmp.data; } void add(int index, T data)// 编号插入 { if (index == 0) { addFirst(data); length++; } else if (index == length) {// 临界 addLast(data); length++; } else { node<T> newpre = head; for (int i = 0; i < index - 1; i++) { newpre = newpre.next; } node<T> newnode = new node(data); newnode.next = newpre.next; newpre.next.pre = newnode; newpre.next = newnode; newnode.pre = newpre; length++; } } void deleteFirst()// 头部删除 { if (length == 1) {// 临界 head = null; tail = head; length--; } else { head.next.pre = null; head = head.next; length--; } } void deleteLast() { if (length == 1) {// 临界 head = null; tail = head; length--; } else { tail.pre.next = null; tail = tail.pre; length--; } } void delete(int index) { if (index == 0) { deleteFirst(); } else if (index == length - 1) { deleteLast(); } else { node tmpp = head; for (int i = 0; i < index - 1; i++) tmpp = tmpp.next; tmpp.next.next.pre = tmpp; tmpp.next = tmpp.next.next; length--; } } void set(int index, T data) { node<T> tmpp = head; for (int i = 0; i < index - 1; i++) tmpp = tmpp.next; tmpp.data = data; } @Override public String toString() { String s = ""; node tmpp = head; while (tmpp != null) { s += tmpp.data + " "; tmpp = tmpp.next; } return s; } public static void main(String[] args) { Doublelinkedlist<Integer> list = new Doublelinkedlist<Integer>(); list.addLast(10); list.addFirst(20); list.add(1, 101); list.addLast(-10); list.addLast(30); list.addFirst(40); System.out.println(list.toString() + " length " + list.length()); list.deleteFirst(); System.out.println(list.toString() + " length " + list.length()); System.out.println(list.toString() + " length " + list.length()); list.delete(1); System.out.println(list.toString() + " length " + list.length()); list.deleteLast(); System.out.println(list.toString() + " length " + list.length()); list.deleteFirst(); System.out.println(list.toString() + " length " + list.length()); } }
40 20 101 10 -10 30 length 6
20 101 10 -10 30 length 5
20 10 -10 30 length 4
20 -10 30 length 3
20 -10 length 2
-10 length 1