自己实现LinkedList底层

来源:互联网 发布:酷开下载软件 编辑:程序博客网 时间:2024/05/22 14:56

手动实现简单的LinkedList

LinkedList底层使用循环双链表实现

//手动实现LinkedList,底层使用双向链表,开始的时候是一个空链表,然后慢慢向其中添加元素package com.ahut.linkedlist;import java.util.Collection;public class MyLinkedList {    private Node first;// 链表的第一个节点    private Node last;// 链表的最后一个节点    private int size;// 链表元素节点的个数// 1.LinkedList的两种构造方法    public MyLinkedList() {    }// 2.往LinkedList中增加数据    public void add(Object obj) {        Node n = new Node();        if (first == null) {// 如果链表为空            n.setPrevious(null);            n.setObj(obj);            n.setNext(null);            first = n;            last = n;        } else {// 如果链表有节点,把节点往last后插            n.setPrevious(last);            n.setNext(null);            n.setObj(obj);            last = n;// n变成新的最后一个节点        }        size++;    }    // 3.获取链表的节点数    public int size() {        return size;    }// 4.获取第i个位置的节点    public Object get(int index) {        checkElementIndex(index);        Node node = node(index);        if (node != null) {// 找到元素了            return node;        }        return null;// 没找到    }// 5.删除第i个位置上的节点    public Node remove(int index) {        checkElementIndex(index);        Node temp = node(index);        if (temp != null) {// 找到第i个位置上的节点            Node up = temp.previous;            Node down = temp.next;            up.next = down;            down.previous = up;        }        size--;        return temp;    }// 6.在第i个位置上插入新的节点    public void add(int index, Object obj) {        checkPositionIndex(index);        if (index == size) {            add(obj);        } else {            Node temp = node(index);            Node newNode = new Node();            newNode.obj = obj;            if (temp != null) {// 找到第i个节点                Node up = temp.previous;                up.next = newNode;                newNode.previous = up;                newNode.next = temp;                temp.previous = newNode;                size++;            }        }    }    // 取得第i个节点的值,不用for循环找,而是一半一半的找    private Node node(int index) {        if (index < (size >> 1)) {// index < size/2            Node temp = null;            for (int i = 0; i < index; i++) {                temp = temp.next;            }            return temp;        } else {// 从后往前找            Node temp = null;            for (int i = size - 1; i > index; i--) {                temp = temp.previous;            }            return temp;        }    }// 检查下标是否越界    public void checkElementIndex(int index) {        if (!(index >= 0 && index < size)) {            throw new IndexOutOfBoundsException();        }    }    public void checkPositionIndex(int index) {        if (!(index >= 0 && index <= size)) {            throw new IndexOutOfBoundsException();        }    }}
0 0
原创粉丝点击