public class LinkList {
class Node<E> {
private E e;
private Node next;
public Node(E e, Node next) {
this.e = e;
this.next = next;
}
public Node(E e) {
this(e, null);
}
public Node() {
this(null, null);
}
}
//链表元素数量
private int size;
//定义一个头节点
private Node head;
public LinkList() {
this.head = null;
this.size = 0;
}
//获取链表元素数量
public int getSize() {
return size;
}
//判断链表是否为空
public boolean isEmpty() {
return size == 0;
}
//在链表头部添加元素
public void pushFirst(E e) {
Node node = new Node(e);
node.next = head;
head = node;
size++;
}
//在链表指定位置添加元素1->2->3->4
public void push(int index, E e) {
if(index < 0 || index > size)
throw new IllegalArgumentException("索引越界");
if(index == 0) {
//在链表头部添加元素
pushFirst(e);
}else{
Node prev = head;
for(int i = 0; i < size - 1; i ++) {
prev = prev.next;
}
Node newNode = new Node(e);
newNode.next = prev.next;
prev.next = newNode;
size++;
}
}
//在链表尾部添加元素
public void pushLast(E e) {
push(size, e);
}
@Override
public String toString() {
Node tail = head;
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append("链表:[");
while(tail.next != null) {
stringBuilder.append(tail.e).append("->");
tail = tail.next;
}
stringBuilder.append(tail.e).append("]");
return stringBuilder.toString();
}
}