Java300学习笔记(8)—— 容器 LinkedList

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u012292754/article/details/86547697

1 自己实现 LinkedList

package day04.mylinkedlist;

public class Node {

    Node previous;
    Object obj;
    Node next;

    public Node() {
    }

    public Node(Node previous, Object obj, Node next) {
        this.previous = previous;
        this.obj = obj;
        this.next = next;
    }

}
package day04.mylinkedlist;

public class MyLinkedList {
    private Node first;
    private Node last;

    private int 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;

            last.next = n;
            last = n;
        }

        size++;
    }

    public Object get(int index) throws Exception {

        rangeCheck(index);

        Node temp = node(index);

        if (temp != null) {
            return temp.obj;
        }

        return null;
    }


    public void remove(int index) {
        rangeCheck(index);

        Node temp = node(index);
        if (temp != null) {
            Node up = temp.previous;
            Node down = temp.next;

            up.next = down;
            down.previous = up;
            size--;
        }

    }


    public int size() {
        return 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 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) {
            temp = first;

            for (int i = 0; i < index; i++) {
                temp = temp.next;
            }

        }

        return temp;

    }

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

}

猜你喜欢

转载自blog.csdn.net/u012292754/article/details/86547697
今日推荐