package offer.linklist; public class LinkList { // 头结点 public Node head; // 当前结点 public Node current; // 添加结点 public void add(int data) { // 判断链表是否为null if (head == null) { // 链表为null,则表示链表中尚未结点 // 头结点为新加入结点 head = new Node(data); // 当前的结点变为头结点 current = head; } else { // 链表不为null,则当前结点的下一个结点为新加入结点 current.next = new Node(data); // 当前的结点变为新加入的结点 current = current.next;// 这一步是关键,别忘!!!! } } // 定义内部类-Node class Node { public int data; public Node next; public Node(int data) { this.data = data; } } // 打印链表 public void printLinkList(LinkList list) { Node current = list.head; while (current != null) { System.out.print("--->" + current.data); current = current.next; } } // 测试链表 public static void main(String[] args) { LinkList list = new LinkList(); for (int i = 0; i < 5; i++) { list.add(i); } list.printLinkList(list); } }