/** * Link节点 * 有数据项和next指向下一个Link引用 */ class Link { private int iData;//数据 private double dData;//数据 public Link next;//下一个link节点的引用 public Link(int i, double d) { iData = i; dData = d; } public String toString() { return "[" + iData + "," + dData + "]"; } public void displayLink() { System.out.println(toString()); } } /** * 链表类 * 维护一个头节点 */ class LinkList { private Link first; /** * 初始化的时候头结点置空 */ public LinkList() { first = null; } /** * 头结点是空代表链表为空 * @return */ public boolean isEmpty() { return first == null; } /** * 向链表头插入Link节点 * @param link */ public void insertFirst(Link link) { link.next = first;//要插入的节点的next指针指向链表的头节点 first = link;//链表的头结点指向被插入的节点 } /** * 从链表头删除头结点并返回 * @return */ public Link deleteFirst() { Link temp = first;//temp临时存上头结点 first = first.next;//将头节点的next指针指向下一个节点 return temp;//返回temp } @Override public String toString() { if (isEmpty()) return "{}"; StringBuilder sb = new StringBuilder(); sb.append("{"); Link current = first; while (current != null) { sb.append(current.toString()); sb.append(","); current = current.next; } sb.deleteCharAt(sb.length() - 1); sb.append("}"); return sb.toString(); } public void displayList() { System.out.println(toString()); } } public class LinkListDemo { public static void main(String[] args) { LinkList ll = new LinkList(); for (int i = 0; i < 10; i++) { Link l = new Link(i, i + 11.23); ll.insertFirst(l); ll.displayList(); } ll.deleteFirst(); ll.deleteFirst(); ll.displayList(); } }