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;i<index;i++){
                    temp = temp.next;
                }
            }else{
                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)); 
    }       
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值