学习目标
更新于(2018-7-13 17:23:08)
自己实现一个LinkedList的部分方法,更好的理解LinkedList类的底层结构!
/**
* 自定义节点
*/
public class Node {
Node pre; //上一节点
Object obj; // 集合对象
Node next; //下一节点
public Node() {
}
public Node(Node pre, Object obj, Node next) {
super();
this.pre = pre;
this.obj = obj;
this.next = next;
}
}
/**
* 自定义LinkedList类
*/
public class MyLinkedList /*implements List*/ {
Node first; //获得头节点
Node last; //获得尾节点
private int size; // 集合大小
/**
* 返回集合大小
*/
public int size(){
return size;
}
/**
* 新增元素
*/
public void add(Object obj){
Node temp = new Node(); // 实例化节点
/**
* 链表中没有任何节点的情况下
*/
if(first==null){
temp.previous =null; // 因为是头结点,所以为空
temp.obj = obj; // 添加当前对象
temp.next = null; // 后面暂时没有节点,所以也为空
//目前第一个和最后一个都是该节点
first = temp;
last = temp;
}else{
/*
* 存在节点直接往last节点后增加新的节点
*/
temp.previous = last; // last紧接上一节点
temp.obj = obj;
temp.next = null; // 后面没节点,为空
last.next = temp; // last的下一节点相当于下一个的头节点
last = temp;
}
size++;
}
/**
* 根据index新增元素到指定位置
*/
public void add(int index,Object obj){
/**
* 调用自定义方法,查找相应节点
*/
Node temp = node(index); // 目标下节点
Node newNode = new Node(); // 目标节点
newNode.obj = obj;
if(temp != null){
Node up = temp.previous; // 目标上一节点
up.next = newNode; // 目标上一节点的下一节点相当于目标节点
/**
* 拼接上下节点,newNode为当前节点
*/
newNode.previous = up;
newNode.next = temp;
/**
* 目标下节点拼接上节点
*/
temp.previous = newNode;
size++;
}
}
/**
* 根据index获取集合元素
*/
public Object get(int index){
rangeCheck(index); // 检查index是否越界
Node temp = node(index);
if(temp!=null){
return temp.obj;
}
return null;
}
/**
* 根据index移除集合元素
*/
public void remove(int index){
Node temp = node(index);
if(temp!=null){ //数据结构的知识,简单逻辑
Node up = temp.previous;
Node down = temp.next;
up.next = down;
down.previous = up;
size--;
}
}
/**
* 越界检查
*/
private void rangeCheck(int index){
if(index<0||index>=size){
try {
throw new Exception();
} catch (Exception e) {
e.printStackTrace();
}
}
}
/**
* 根据索引找到相应节点
*/
public Node node(int index){ //实现List接口必须有的方法
Node temp = null;
if(first!=null){
if (index < (size >> 1)) { //如果索引号是前半部分的则从头结点开始遍历查找
temp = first;
for(int i=0;i<index;i++){
temp = temp.next;
}
}else{
temp = last; //如果索引号是后半部分的则从尾结点开始遍历查找
for (int i = size - 1; i > index; i--){
temp = temp.previous;
}
}
}
return temp;
}
/**
* 简单测试
*/
public static void main(String[] args) {
MyLinkedList list = new MyLinkedList();
list.add("aaa");
list.add("bbb");
list.add("ccc");
list.add("ddd");
list.add("eee");
list.add(4, "11111111111");
list.remove(3);
for(int i = 0; i < list.size(); i++){
System.out.println(list.get(i));
}
}
}