单向链表
添加元素和反转
import lombok.Data; @Data public class Link{ // 有了这个东西其他就好操作了 private Node pre = new Node<>(null); private Node tail; public Node getHead() { return pre.getNext(); } public void append(T data) { if (tail == null) { tail = new Node<>(data); pre.setNext(tail); } else { tail.setNext(new Node<>(data)); tail = tail.getNext(); } } public void revert() { Node p = pre.next; Node q = p.next; p.next = null; while (q != null) { Node node = q.next; q.next = p; p = q; q = node; } pre.next = p; } @Data public static class Node { public Node(T data) { this.data = data; } private T data; private Node next; } public static void main(String[] args) { final Link link = new Link<>(); for (int i = 0; i < 5; i++) { link.append((char) (i + 'a')); } Node node = link.getHead(); while (node != null) { System.out.println(node.getData()); node = node.getNext(); } System.out.println("----------"); link.revert(); node = link.getHead(); while (node != null) { System.out.println(node.getData()); node = node.getNext(); } } }



