自己封装实现一个的LinkedList集合类

一、LinkedList具体实现:

我们先看一下,java为我们提供LinkedList是什么样子的:

LinkedList是一种双向链表结构的集合,我们可以通过LinkedList提供的Node类可知,在Node中有三个成员变量(item、next和prev),item存储当前节点的值,next指向当前节点的下一个节点,prev指向当前节点的上一个节点,所以我们说LinkedList是一种双向链表。

private static class Node<E> {
    E item;
    Node<E> next;
    Node<E> prev;

    Node(Node<E> prev, E element, Node<E> next) {
        this.item = element;
        this.next = next;
        this.prev = prev;
    }
}

LinkedList作为一种链表结构的集合,它的数据维护方式与ArrayList有显著的不同,ArrayList底层是通过数组实现的,ArrayList是在内存中申请的一组连续的内存空间,可以通过下标很容易的找到对应的存储位置,进行数据的维护,LinkedList的添加操作是将新增的数据直接链接到数据链表的尾部。

/**
 * Appends the specified element to the end of this list.
 *
 * <p>This method is equivalent to {@link #addLast}.
 *
 * @param e element to be appended to this list
 * @return {@code true} (as specified by {@link Collection#add})
 */
public boolean add(E e) {
    linkLast(e);
    return true;
}
/**
 * Links e as last element.
 */
void linkLast(E e) {
    final Node<E> l = last;
    final Node<E> newNode = new Node<>(l, e, null);
    last = newNode;
    if (l == null)
        first = newNode;
    else
        l.next = newNode;
    size++;
    modCount++;
}

LinkedList的删除操作,先检查出入的index参数是否符合规定,index这个值必须大于等于0并且小于size,然后调用node()进行元素的查找。

/**
 * Removes the element at the specified position in this list.  Shifts any
 * subsequent elements to the left (subtracts one from their indices).
 * Returns the element that was removed from the list.
 *
 * @param index the index of the element to be removed
 * @return the element previously at the specified position
 * @throws Index
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值