java 集合类-LinkedList

[size=medium]接上文 - java 集合类-ArrayList[/size]


LinkedList的底层实现方法:双向链表。

LinkedList用静态内部类Entry来表示一个节点,定义一个 header节点。

Entry内部定义了 前驱节点和后驱节点 以及存储数据。

LinkedList 源码:
public class LinkedList<E>
extends AbstractSequentialList<E>
implements List<E>, Queue<E>, Cloneable, java.io.Serializable
{
private transient Entry<E> header = new Entry<E>(null, null, null);
private transient int size = 0;

/**
* Constructs an empty list.
*/
public LinkedList() {
header.next = header.previous = header;
}


内部类 Entry 源码:
   
private static class Entry<E> {
E element;
Entry<E> next; //后置节点
Entry<E> previous;//前驱节点

Entry(E element, Entry<E> next, Entry<E> previous) {
this.element = element;
this.next = next;
this.previous = previous;
}
}



LinkedList add方法源码 :

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

//将新添的数据增加到链表模型中,参考下图。
private Entry<E> addBefore(E o, Entry<E> e) {
Entry<E> newEntry = new Entry<E>(o, e, e.previous);
newEntry.previous.next = newEntry;
newEntry.next.previous = newEntry;
size++;
modCount++;
return newEntry;
}


增加后双向链表的数据模型如下:
[img]http://dl.iteye.com/upload/attachment/0062/1037/756796a2-2037-3dbb-842e-562d658d6760.jpg[/img]


LinkedList get方法源码:
 
public E get(int index) {
return entry(index).element;
}
//找到对应的Entry对象。
private Entry<E> entry(int index) {
if (index < 0 || index >= size)
throw new IndexOutOfBoundsException("Index: "+index+
", Size: "+size);
Entry<E> e = header;
//index 与 size/2 进行比较 确定前驱查找或是后驱查找
//具体查找可参考上图模型。
//如若 size > 10, index=1 ,
//则查找对象相当于 Entry e = header.next.next;
if (index < (size >> 1)) {
for (int i = 0; i <= index; i++)
e = e.next;
} else {
for (int i = size; i > index; i--)
e = e.previous;
}
return e;
}


LinkedList 删除方法源码:

    public E remove(int index) {
return remove(entry(index));
}

private Entry<E> entry(int index) {
if (index < 0 || index >= size)
throw new IndexOutOfBoundsException("Index: "+index+
", Size: "+size);
Entry<E> e = header;
if (index < (size >> 1)) {
for (int i = 0; i <= index; i++)
e = e.next;
} else {
for (int i = size; i > index; i--)
e = e.previous;
}
return e;
}

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

E result = e.element;
//关联删除节点左右两边的节点
//如上图:若删除第一个节点,则将header与第二个节点相互关联上即可。
e.previous.next = e.next;
e.next.previous = e.previous;
e.next = e.previous = null;
e.element = null;
size--;
modCount++;
return result;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值