LinkedList Source code 1.6

private transient Entry header = new Entry(null, null, null);

private transient int size = 0;

/**

* Constructs an empty list.

*/

public LinkedList() {

header.next = header.previous = header;

}

LinkedList 是一个双向链表

表头和表位都是header同一对象

header->e->e->e->header

两个header是同一对象

这样就形成了闭环,只要有header对象,无论从前向后还是从后向前都能追溯到元素

get()方法体现了这一特点

public E get(int index) {

return entry(index).element;

}

/**

* Returns the indexed entry.

*/

private Entry entry(int index) {

if (index < 0 || index >= size)

throw new IndexOutOfBoundsException("Index: "+index+

", Size: "+size);

Entry 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;

}

遍历

public Object[] toArray() {

Object[] result = new Object[size];

int i = 0;

for (Entry e = header.next; e != header; e = e.next)

result[i++] = e.element;

return result;

}

linkedlist 对删除、增加的效率比较高

查询的效率因为要不断的沿着链表查询所以效率相对比较慢

尾插法插入集合

public boolean addAll(int index, Collection c) {

if (index < 0 || index > size)

throw new IndexOutOfBoundsException("Index: "+index+

", Size: "+size);

Object[] a = c.toArray();

int numNew = a.length;

if (numNew==0)

return false;

modCount++;

Entry successor = (index==size ? header : entry(index));

Entry predecessor = successor.previous;

for (int i=0; i

Entry e = new Entry((E)a[i], successor, predecessor);

predecessor.next = e;

predecessor = e;

}

successor.previous = predecessor;

size += numNew;

return true;

}

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 背景 一年多以前我在知乎上答了有关LeetCode的问题, 分享了一些自己做题目的经验。 张土汪:刷leetcod...
    土汪阅读 14,349评论 0 33
  • ``` /* * ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject ...
    非专业码农阅读 2,701评论 0 0
  • 临近春节,很多消费者忽然发现,滴滴打车很难叫到车,如果不加价,不加很多价,就基本上没法叫到车;在路边想招手拦车,也...
    五月菡萏阅读 2,444评论 0 0
  • 夜色茫茫,寒风在车窗外呼啸。车子在道路上疾驰,两旁的树木,飞速而过,就像是进了一个怪物的血盆大口。许克把车速开到了...
    熊路漫阅读 3,805评论 2 7
  • 懂事起,我知道父亲流过两次泪。 第一次,我没亲眼目睹,是听母亲说起的。父亲送我去大学报道后自己坐火车回家,嚎啕大哭...
    往往时候阅读 4,655评论 0 0