java需要关注的知识点---LinkedList

LinkedList是采用双向链表来存储数据:

[color=red][b]LinkedList允许插入null的值[/b][/color]
双向链表的结构图:

[img]http://dl.iteye.com/upload/attachment/594272/3436e4ec-0d11-3447-b29a-f3fdbdd4bd2e.jpg[/img]

LinkedList的构造函数:

public LinkedList() {
header.next = header.previous = header;
}

LinkedList在构造函数中初始化双向链表的表头header,指定header的上一个和下一个都是自己。
LinkedList的add方法:

public boolean add(E e) {
addBefore(e, header);
return true;
}

在进行插入元素的时候,传入插入元素和header.
[color=darkred][u][b]LinkedList的addBefore方法:[/b][/u][/color]

private Entry<E> addBefore(E e, Entry<E> entry) {
Entry<E> newEntry = new Entry<E>(e, entry, entry.previous);
newEntry.previous.next = newEntry;
newEntry.next.previous = newEntry;
size++;
modCount++;
return newEntry;
}

[u][color=red][b]LinkedList插入元素的过程(addBefore方法执行操作的图示):[/b][/color][/u]
刚刚开始:
空head:

[img]http://dl.iteye.com/upload/attachment/594499/78a0e1bf-2d59-3441-9b13-40c21a24703c.gif[/img]

插入元素第一个元素e:

[img]http://dl.iteye.com/upload/attachment/594488/8b66fe5d-398c-3ac5-8e80-a7b48855c806.gif[/img]

插入第二个元素e2:
指针指向:

[img]http://dl.iteye.com/upload/attachment/594492/f1808bb9-6a81-3f26-a015-b72431ebc242.gif[/img]

删除已经失效的指针效果图:

[img]http://dl.iteye.com/upload/attachment/594491/bb29570d-c8e1-36cb-8627-d6286744d7df.gif[/img]

插入第三个元素e3:

指针指向:


[img]http://dl.iteye.com/upload/attachment/594509/001b9591-d8d0-33d1-a834-b8fa1f9331f6.gif[/img]


删除已经失效的指针效果图:


[img]http://dl.iteye.com/upload/attachment/594511/ae5473ad-f875-3a7a-8e59-8ff7afd614fe.gif[/img]


示图中,的2X1表示的是,指针指向e2,不再指向e,所以该指向不存在。

LinkedList 的remove方法:

private E remove(Entry<E> e) {
if (e == header)
throw new NoSuchElementException();

E result = e.element;
e.previous.next = e.next;
e.next.previous = e.previous;
e.next = e.previous = null;
e.element = null;
size--;
modCount++;
return result;
}

删除前:


[img]http://dl.iteye.com/upload/attachment/594396/4441f890-e05e-3f42-8ac0-284b0f5d0bf9.gif[/img]


删除操作:


[img]http://dl.iteye.com/upload/attachment/594398/24e7f31c-21f0-3ea8-8e4c-94ec976c197a.gif[/img]


程序最后设置e.next,e.previous,e.element为null,虚拟机会回收该快 内存。

LinkedList的addFirst方法(在head之后插入元素)。

public void addFirst(E e) {
addBefore(e, header.next);
}

图示:
1:

[img]http://dl.iteye.com/upload/attachment/594571/0c7ef90f-23d7-3e95-8c2a-196166c10b1c.gif[/img]

2:插入后指针效果图:

[img]http://dl.iteye.com/upload/attachment/594573/f1e0227e-a6f7-3096-b76c-f52c278083b2.gif[/img]

3:最后效果图:

[img]http://dl.iteye.com/upload/attachment/594575/c12007dc-5d5a-3c1d-a11e-e9d0d167f19c.gif[/img]
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值