方法:
package com.MyCollection;
/**
* 自定义链表
* 增加remove方法
* @author Lucifer
*/
public class LcfLinkedList03 {
private Node first;
private Node last;
private int size;
/*链表的remove方法---修改节点指向即可*/
//根据索引值拿到节点,进行判断,如果节点不为空,把自己删掉。删掉的方法是它的上一个节点直接指向它的下一个节点
public void remove(int index){
//创建临时节点,将获取到的节点信息赋值给临时节点
Node temp = getNode(index);
//进行判断---考虑第一个元素
if (temp != null){
//创建两个对象代表节点
Node up = temp.previous; //创建一个Node对象代表上一个节点
Node down = temp.next; //创建一个Node对象代表下一个节点
if (up != null){
up.next = down; //目标节点的上一个节点的尾节点直接指向目标节点的下一个节点
}
if (down != null){
down.previous = up; //等于空为第一个元素,就不做这样的操作了
}
/*
如果是0号索引的元素,只会执行down != null这一句
这样的话上一个指针就是null,所以要为头部和尾部单独写一个方法
*/
//被删除的元素是第一个
if (index == 0){
//头节点直接等于下一个尾节点
first = down;
}
//被删除的元素是最后一个
if (index == size - 1){
//尾部节点等于上一个节点up
last = up;
}
size--;
}
}
public void add(Object obj){
Node node = new Node(obj);
if (first == null){
first = node;
last = node;
}else {
node.previous = last;
node.next = null;
last.next = node;
last = node;
}
size++;
}
public Object get(int index){
if (index < 0 || index > size - 1){
throw new RuntimeException("索引数字不合法" + index);
}
//调用下面封装好的重置方法
Node temp = getNode(index); //index是方法定义的形参
return temp !=