基本数据结构——链表
链表中各个对象按线性顺序排列,链表的顺序是由各个对象里的指针决定的。
链表中每个元素都是一个对象。每个对象中包含一个关键字key和两个指针prev, next分别指针这个对象的前一个对象和下一个对象。关键方法的实现代码如下:
//定义插入,删除,查找方法 public class List<E> { private Node<E> first; //Pointer to first node. private Node<E> last; //Pointer to last node. private int size; public void insertFirst(E e) { Node<E> f = first; Node<E> newNode = new Node<E>(null, f, e); first = newNode; if(f == null){ last = newNode; }else{ f.prev = newNode; } size++; } public Node<E> research(E e) { Node<E> temp = first; while(temp != null && temp.key != e ) { temp = temp.next; } return temp; } public void deleteLast() { Node<E> l = last; final E element = l.key; final Node<E> prev = l.prev; l.key = null; l.prev = null; // help GC last = prev; if (prev == null) first = null; else prev.next = null; size--; } private static class Node<E> { Node<E> prev; Node<E> next; E key; public Node(Node<E> prev, Node<E> next, E key) { this.prev = prev; this.next = next; this.key = key; } } /* public static void main(String[] args) { List<Integer> list = new List<>(); list.insertFirst(1); list.insertFirst(2); list.insertFirst(3); list.insertFirst(4); list.insertFirst(5); Node<Integer> node = list.research(1); System.out.println(node); System.out.println(list.size); list.deleteLast(); node = list.research(1); System.out.println(node); System.out.println(list.size); }*/ }