package com.liangyumingblog; public class LinkList { private class Node { int value; Node next; public Node(int value, Node next) { this.value = value; this.next = next; } } private Node head = new Node(-1, null); private int size = 0; public void add(int value) { size++; Node current = head; while (current.next != null) { current = current.next; } current.next = new Node(value, null); } public Node getLast() { Node current = head; while (current.next != null) { current = current.next; } return current; } public Node removeLast() { Node current = head; while (current.next.next != null) { current = current.next; } Node tmp = current.next; current.next = null; tmp.next = null; return tmp; } public void reverse() { int length = 0; while (length != size) { insert(length, removeLast()); length++; } } public boolean insert(int index, Node node) { if (index > size) { return false; } int now = 0; Node current = head; while (now != index) { ++now; current = current.next; } Node tmp = current.next; current.next = node; node.next = tmp; return true; } @Override public String toString() { StringBuffer stringBuffer = new StringBuffer(); stringBuffer.append("["); Node current = head; while (current.next != null) { if (head != current) { stringBuffer.append(current.value); stringBuffer.append(", "); } current = current.next; } stringBuffer.append(current.value); stringBuffer.append("]"); return stringBuffer.toString(); } }