特点:
插入快删除快 相较于数组 不需要扩容 ,因为他在内存中不是连续的空间
查询和
public class MyLinkedList<E> implements MyList<E> {
Node hand = null;
class Node {
Node next = null;
E obj;//保存的数据
public Node(E obj) {
this.obj = obj;
}
}
@Override
public int size() {
int size = 0;
Node var1 = hand;
while (var1 != null) {
size++;
var1 = var1.next;
}
return size;
}
@Override
public boolean add(E obj) {
Node node = new Node(obj);
if (hand == null) {
hand = node;
return true;
}
//从根节点开始,找到下个节点为空的对象
Node var1 = hand;
while (var1.next != null) {
var1 = var1.next;
}
//关联数据
var1.next = node;
return true;
}
@Override
public boolean remove(E obj) {
if (hand.obj == obj) {
hand = hand.next;
return true;
}
Node var1 = hand;
while (var1.next != null) {
if (var1.next.obj == obj) {
var1.next = var1.next.next;
return true;
} else var1 = var1.next;
}
return false;
}
@Override
public E get(int index) {
rangeCheck(index);
if (index == 0) {
return hand.obj;
}
Node var1 = hand;
for (int node_next = 0; node_next < index; node_next++)
var1 = var1.next;
return var1.obj;
}
@Override
public E set(int index, E obj) {
rangeCheck(index--);
Node var1 = hand;
if (index == 0) {
hand.obj = obj;
return obj;
}
for (int node_next = 0; node_next < index; node_next++)
var1 = var1.next;
var1.obj = obj;
return var1.obj;
}
@Override
public E remove(int index) {
rangeCheck(index);
if (index == 0) {
hand = hand.next;
return hand.obj;
}
Node var1 = hand;
index--;
for (int node_next = 0; node_next < index; node_next++)
var1 = var1.next;
var1.next = var1.next.next;
return var1.obj;
}
@Override
public void clear() {
if (hand != null)
hand.next = null;
}
}
来源:CSDN
作者:李东101
链接:https://blog.csdn.net/qq_36183235/article/details/103848071