TriyHoo

做好一件事需要的是专注和持之以恒

  博客园 :: 首页 :: 新随笔 :: 联系 :: 订阅 :: 管理 ::

j2se学习笔记四

  今天自己实现了一下容器类中的LinkedList类,LinkedList的底层是以双链表结构实现的,所以LinkedList在查询方面效率较慢,在插删改效率较高,以为不需要移动元素。

  首先,因为LinkedList的数据结构是链表,即每个元素存储在节点中,所以操作对象是以节点(Node)为单位。JDK源码中也是以node标识,Node类中需要三个成员变量,即 Node previous(存储前驱节点的引用),Object obj(节点存储的数据对象),Node next(后置节点的引用)。一下是自己实现的LinkedList代码,只是实现了add(),remove(),get(),node()等几个基本的方法。

package mylist;

import java.util.Date;

public class MyLinkedList {

    public Node first;
    public Node last;
    public int size;

    public static void main(String[] args) {

        MyLinkedList list = new MyLinkedList();
        list.add("a");
        list.add("b");
        list.add(new Date());
        // list.get(0);
        list.remove(0);
        System.out.println(list.get(1));
        System.out.println(list.size());
    }

    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 {
            n.previous = last;
            n.obj = obj;
            n.next = null;
            n.previous.next = n;
            last = n;
        }
        size++;
    }

    public Object get(int index) {
        return node(index).obj;
    }

    public void remove(int index) {
        Node temp = node(index);
        if(temp == first) {
            temp.next.previous = null;
            first = temp.next;
        }
        else if(temp!=null) {
            Node front = temp.previous;
            Node next = temp.next;
            front.next = next;
            next.previous = front;
            }
        size--;
    }

    public Node node(int index) {
        rangeCheck(index);
        Node temp = first;
        if (index == 0) {
            return temp;
        } else {
            for (int i = 0; i < index; i++) {
                temp = temp.next;
            }
            return temp;
        }
    }

    public void rangeCheck(int index) {
        if (index < 0 || index > size) {
            try {
                throw new Exception();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    public int size() {
        return size;
    }
}

  由此可见,数据结构的重要性,对于理解底层的容器类非常有帮助,我也是还在学习的路上,只有理解了实现的原理,自己手写链表才可以手到擒来。给自己加油,熟能生巧,不断地练习终有一天会使自己变得更好的!

 

芝兰生于幽林,不以无人而不芳;

君子修道立德,不以穷困而改节;

posted on 2014-12-12 11:53  TriyHoo  阅读(71)  评论(0)    收藏  举报