1. Node节点
public class Node<T> {
private Node<T> pre;
private Node<T> next;
private T data;
public Node() {
}
public Node getPre() {
return pre;
}
public void setPre(Node pre) {
this.pre = pre;
}
public Node getNext() {
return next;
}
public void setNext(Node next) {
this.next = next;
}
public T getData() {
return data;
}
public void setData(T data) {
this.data = data;
}
public Node(Node pre, Node next, T data) {
this.pre = pre;
this.next = next;
this.data = data;
}
}
2.MyLinkedList
public class MyLinkedList<T>{
private Node<T> head;
private Node<T> tail;
private int size;
public MyLinkedList() {}
public MyLinkedList(Node<T> head) {
this.head = head;
}
public void add(T data) {
if (head == null) {
Node<T> node = new Node<>();
node.setData(data);
head = node;
tail = node;
} else {
Node<T> node = new Node<>();
node.setData(data);
node.setPre(tail);
node.setNext(null);
tail.setNext(node);
tail = node;
}
size++;
}
public int size() {
return size;
}
public T get(int index) {
if (index < 0 || index >= size) throw new IndexOutOfBoundsException("Index: " + index + ", Size: " + size);
Node<T> node = head;
for (int i = 0; i < index; i++) {
node = node.getNext();
}
return (T)node.getData();
}
}
3. LinkedListTest 测试类
public class LinkedListTest {
public static void main(String[] args) {
MyLinkedList<String> list = new MyLinkedList<>();
list.add("aa");
list.add("bb");
list.add("cc");
String result = list.get(1);
System.out.println(result);
}
}