public class LinkedList<T> {
private Node head; // 头节点
private Node tail; // 尾节点
private int size; // 链表大小
public boolean isEmpty() {
public void addFirst(T data) {
Node newNode = new Node(data);
public void addLast(T data) {
Node newNode = new Node(data);
public void add(int index, T data) {
if (index < 0 || index > size) {
throw new IndexOutOfBoundsException("Index: " + index + ", Size: " + size);
Node prev = getNode(index - 1);
Node newNode = new Node(data);
newNode.next = prev.next;
throw new IllegalStateException("List is empty");
throw new IllegalStateException("List is empty");
Node prev = getNode(size - 2);
public T remove(int index) {
if (index < 0 || index >= size) {
throw new IndexOutOfBoundsException("Index: " + index + ", Size: " + size);
Node prev = getNode(index - 1);
prev.next = prev.next.next;
public T get(int index) {
if (index < 0 || index >= size) {
throw new IndexOutOfBoundsException("Index: " + index + ", Size: " + size);
return getNode(index).data;
public void set(int index, T data) {
if (index < 0 || index >= size) {
throw new IndexOutOfBoundsException("Index: " + index + ", Size: " + size);
getNode(index).data = data;
public int indexOf(T data) {
while (current != null) {
if (current.data.equals(data)) {
private Node getNode(int index) {
for (int i = 0; i < index; i++) {
System.out.print("List: ");
while (current != null) {
System.out.print(current.data + " ");