LinkedList的底层是基于双向链表实现的,所以查询慢,增删改快,但是线程不安全,效率较高。
package com.liqiang.jdk;
/**
* 1.LinkedList的简单实现
* 2.后续有时间会逐步添加方法
* 3.实现的方法有:
* void add(Object obj)
* void add(int index,Object obj)
* int size()
* Object get(int index)
* void remove(int index)
* Node node(int index)
* void rangeCheck(int index)
*/
class Node{
Object obj;
Node previous;
Node next;
public void setObj(Object obj){
this.obj = obj;
}
public void setPrevious(Node previous){
this.previous = previous;
}
public void setNext(Node next){
this.next = next;
}
public Node(Object obj,Node previous,Node next){
this.obj = obj;
this.previous = previous;
this.next = next;
}
public Node(){
}
}
public class MyLinkedList<E> {
private Node first = null;
private Node last = null;
private int size = 0;
/*
* 1.创建新节点,以便实现添加
* 2.要对头节点判断是否为空,空的话将指定对象置为头节点
* 3.不为空,则往last后增加节点
* 4.同时生成新的last
* 5.size++
* */
public void add(Object obj) {
Node node = new Node();
if (first == null) {
node.setPrevious(null);
node.setObj(obj);
node.setNext(null);
first = node;
last = node;
} else {
node.setPrevious(last);
node.setObj(obj);
node.setNext(null);
last.setNext(node);
last = node;
}
size++;
}
/*
* 1.生成新节点
* 2.遍历链表
* 3.判断遍历得到的节点是否为空,不空则插入
* 4.size++
* */
public void add(int index, Object obj) {
Node temp = node(index);
Node node = new Node();
node.setObj(obj);
if (temp != null) {
node.setPrevious(temp.previous);
temp.previous.next = node;
node.next = temp;
temp.previous = node;
}
size++;
}
public int size() {
return size;
}
public Object get(int index) {
/*
* 1.获得指定序列的结点
* 2.对序列的合法性判断
* 3.对结点的遍历
* 4.结点不为空,返回结点的数据域
*/
rangeCheck(index);
Node temp = node(index);
if (temp != null) {
return temp.obj;
}
return null;
}
public void remove(int index) {
Node temp = node(index);
if (temp != null) {
temp.next.previous = temp.previous;
temp.previous.next = temp.next;
size--;
}
}
public Node node(int index) {
Node temp = null;
if (first != null)
temp = first;
for (int i = 0; i < index; ++i)
temp = temp.next;
return temp;
}
private void rangeCheck(int index) {
/*
* 对序列的合法性检查
*/
if (index < 0 || index >= size) {
try {
throw new Exception();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public static void main(String[] args) {
MyLinkedList list=new MyLinkedList();
list.add("你好");
list.add("哦哦");
list.add("Java");
list.add("谢谢");
list.remove(1);
list.add(1,"我的爱");
list.add(2,"我喜欢你");
System.out.println(list.size());
System.out.println(list.get(1));
System.out.println(list.get(2));
}
}