LinkedList实现:
package cn.meowrain.Datastructure.collection;
public class LinkedList<E> {
//链表的头结点,用于连接之后的所有结点
private final Node<E> head = new Node<>(null);
private int size;
public void add(E element, int index) {
if (index < 0 || index > size) {
throw new IndexOutOfBoundsException("错误范围,位置不合法,合法范围为:0~" + size);
}
Node<E> prev = head;
for (int i = 0; i < index; i++) {
prev = prev.next;
}
Node<E> node = new Node<>(element);
node.next = prev.next;
prev.next = node;
size++;
}
private static class Node<E> {
private final E element;
private Node<E> next;
public Node(E e) {
this.element = e;
}
}
public int size() {
return size;
}
public E remove(int index){
if(index<0||index>size-1)
throw new IndexOutOfBoundsException("删除位置非法,合法删除位置范围为: 0~"+ (size-1));
Node<E> prev = head;
for(int i = 0;i<index;i++){
prev = prev.next;
}
E element = prev.next.element;
prev.next = prev.next.next;
return element;
}
public E get(int index){
if(index<0||index>size-1)
throw new IndexOutOfBoundsException("获取位置非法,合法获取位置范围为: 0~"+ (size-1));
Node<E> prev = head;
for(int i = 0;i<=index;i++){
prev = prev.next;
}
E element = prev.element;
return element;
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
Node<E> node = head.next;
while (node != null) {
builder.append(node.element).append(" ");
node = node.next;
}
return builder.toString();
}
}
```
## LinkedListRunner.java
```java
package cn.meowrain.Datastructure;
import cn.meowrain.Datastructure.collection.LinkedList;
public class LinkedListRunner {
public static void main(String[] args) {
LinkedList<String> list = new LinkedList<>();
list.add("bbb",0);
list.add("ccc",1);
list.add("ddd",2);
System.out.println(list);
System.out.println(list.size());
String a = list.remove(1);
System.out.println(a);
System.out.println(list);
list.add("ccc",1);
System.out.println(list.get(1));
}
}
```