103-104_容器_JDK源代码分析_自己实现LinkedList

public class MyLinkedList/*implements List*/{
    class Node{
        Node previous;
        Object obj;
        Node next;
    }
    private Node first;
    private Node last;

    private int size;

    public int size(){
        return 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){
        Node temp = null;
        if(first!=null){
            if (index < (size >> 1)) {
                temp = first;
                for(int i=0;ielse{
                temp = last;
                for (int i = size - 1; i > index; i--){
                    temp = temp.previous;
                }
            }   
        }
        return temp;
    }
    public void add(Object obj){
        Node n = new Node();
        if(first==null){
            n.previous=null;
            n.obj=obj;
            n.next=null;

            first = n;
            last = n;
        }else{
            //直接往last节点后增加新的节点
            n.previous=last;
            n.obj=obj;
            n.next=null;
            last.next=n;
            last = n;
        }
            size++;
    }

    public Object get(int index){   //2
        rangeCheck(index);
        // 0 1 2 3 4
        Node temp = node(index);
        if(temp!=null){
            return temp.obj;
        }
        return null;
    }

    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--;
        }
    }

    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.previous = up;

            newNode.next = temp;
            temp.previous = newNode;

            size++;
        }
    }

    public static void main(String[] args) {
        MyLinkedList list = new MyLinkedList();
        list.add("aaa");
        list.add("bbb");
//      list.add(1,"BBBB");
        list.add("ccc");
        list.add("ddd");
        list.add("eee");
//      list.remove(1);
        System.out.println(list.get(3)); 
    }       
}

你可能感兴趣的:(Java基础,List,linkedlist,源代码)