public class MyLinkedList {
//MyLinkedList存储数据个数
int size;
//首节点
Node first;
//尾节点
Node last;
//添加数据
public boolean add(Object o) {
Node node = new Node(last, o, null);
//如果尾节点为空,即MyLinkedList没有数据把添加的数据设置为首节点否则把已有的尾节点的next指向该数据
if (last == null) {
first = node;
} else {
last.next = node;
}
//新添加的数据设置为节点之后,把该节点设置为尾节点
last = node;
//长度++
size++;
return true;
}
//删除数据
public Object remove(int index) {
//通过下标获得要删除节点获取其中数据,值、前一个节点、后一个节点
Node node = node(index);
Object value = node.value;
Node pro = node.pro;
Node next = node.next;
//验证下标合法性
if (index >= 0 && index < size) {
//如果该节点没有前一个节点,即该节点为首节点,将该节点的下一个节点设置为首节点
if (pro == null) {
next.pro = null;
node.next = null;
first = next;
}
//如果该节点没有下一个节点,即该节点为为节点,将该节点的上一个节点设置为尾节点
else if (next == null) {
pro.next = null;
node.pro = null;
last = pro;
}
//如果该节点既不是首节点也不是尾节点,将该节点的上一个节点的next指向该节点的下一个节点,将该节点的下一个节点的pro指向该节点的上一个节点
else{
pro.next = next;
next.pro = pro;
}
//最后将该节点置空,长度减一
node = null;
size--;
} else {
System.out.println("不存在该序号元素");
}
return value;
}
//修改
public void set(int index, Object o) {
if (index >= 0 && index < size) {
Node node = node(index);
node.value = o;
}else {
System.out.println("不存在该序号元素");
}
}
public Object get(int index){
return node(index).value;
}
//查询
public Node node(int index) {
//当查询的下标小于长度一半时从尾部从头部遍历,否则从尾部遍历
if (index < (size >> 1)) {
Node x = first;
for (int i = 0; i < index; i++) {
x = x.next;
}
return x;
} else {
Node x = last;
for (int i = size - 1; i > index; i--) {
x = x.pro;
}
return x;
}
}
class Node {
Object value;
Node pro;
Node next;
public Node(Node pro, Object value, Node next) {
super();
this.value = value;
this.pro = pro;
this.next = next;
}
}
}
LinkedList底层简化版实现
最新推荐文章于 2024-12-02 22:07:36 发布